Domanda

Is there any way to to add custom compile time errors when there is a mismatch in number of arguments passed to String.Format in C#

Eg:

String.Format("{0} and {1} are my pets", animal);

the above line should throw an error since we have passed only one argument "animal" , while it is expecting two {0},{1}.. but in reality it throws just run time errors.

È stato utile?

Soluzione

FxCop / Code Analysis will pick this up. And yes, you can do that at compile time in VS Premium / Ultimate.

enter image description here

Altri suggerimenti

Resharper will add an IDE warning for that. However, that isn't a compiler error; what you have written is perfectly fine as far as the compiler is concerned.

enter image description here

You can't add custom compile time error. Its a logical error and will throw exception

Edit:

Console.WriteLine(string.Format("test{0} and {1}","test"));

it will throw:

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

This is a terrible idea, but you could create five or so extension methods called Format1, Format2, etc. and have the parameters hard coded and passed to a normal String.Format.

Format strings are a feature of certain methods in the .NET class library. The compiler doesn't know anything about them. The compiler can only throw errors regarding things that have to do with the language itself, not how you invoke certain library functions.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top