Reputation: 1429
In C#, I noticed that using string.Format with numeric indexing could be dangerous. I use it often for logging. Incorrect mapping would result into exception:
Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
Example:
Console.Log(string.Format("test string: var1: {0}, var2:{1}, var3:{2}", var1, var2); // using two arguments but three mappings in log string.
I feel something like this which can run into Exception should really be Compiler Error than Warning. I understand .Net framework would not be able to do it because it receives arguments in params[].
Being honest, but I do ignore compiler warnings in my solution. Not because I don't find them important but because there are too many warnings generated from code submitted by others in the repository.
Questions: 1. Is there a good way in Visual Studio to get Compilation Errors for certain warnings. 2. Is there a better coding practice I can follow for such thing to avoid mistake like this.
Upvotes: 0
Views: 1092
Reputation: 6947
Answer for Question 1. Yes
You have to enable 'treat warnings as errors'
Source: This SO Question, from Googling and I tested it myself
Answer for Question 2: I think this is highly subjective, so it's more opinion based. Maybe instead of manually typing them as var1, var2, var3 you could have distinctively made them a group, use a for-loop etc.
And well, unit tests. That's one of the most important things, even if everyone hates them. Check out this book: Code Complete by Steve McConnell as a recommended resource. It's used in many university courses on Program Design and Development too.
Upvotes: 2