views:

63

answers:

3

Is there any way to check the format string at compile time ?

Example:

Console.WriteLine("{0} is a really {1} site", "stackoverflow.com", "cool");//this will run

//this will give an exception as only one argument is supplied

Console.WriteLine("{0} is a really {1} site", "stackoverflow.com");

Exception:"Index (zero based) must be greater than or equal to zero and less than the size of the argument list."

and if format string is not in the correct format (i.e. missing the "}" after 1 here )

Console.WriteLine("{0} is a really {1 site", "stackoverflow.com","cool");

Exception: Input string was not in a correct format.
+2  A: 

No, there is no way to do this. Unit testing solves this problem.

Josh Stodola
+2  A: 

While not really compile-time checking, ReSharper can warn you in Visual Studio when the number of arguments is wrong or the format string is in the wrong format.

Joey
+3  A: 

No, you can't add compile-time verification here. This is one of the down-sides to resource strings and formatting strings. You can do a few things to mitigate your problem.

  1. Thoroughly unit test your public interfaces to be confident that your strings are being formatted correctly.
  2. Use tools like ReSharper that can perform static analysis and let you know about these problems before you run your application.
  3. Things are better threes.
Ed Altorfer