Home > work > How to validate string.format within Visual Studio

How to validate string.format within Visual Studio

 

In writing code we use string.format a lot to create strings for error reporting or sending to the screen. Some of these will only ever get created if an error occurs so they become difficult to test to make sure the don’t throw an error. Take the following example

The following code would fail at runtime but is fine in the compiler

string.Format("{0} This is valid but will error {1}", this.siteURL);

So how do we catch these. Well we all use the code analysis tools built into visual studio. Don’t we?

 

Well this has a nice test case that will catch and highlight this problem.

 

Run code analysis on your project Alt+F11 or select “Run Code Analysis on …” from the Analyse menu.

 

Then once this has finished you can search for issue CA2241. This will show any and all string.formats that would fail at run time.

 

It would be nice if the compiler caught these but this is still a good approach.

Advertisements
Categories: work Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: