0

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.

dwcanillas
  • 3,562
  • 2
  • 24
  • 33
vinayvasyani
  • 1,393
  • 4
  • 13
  • 34
  • 1
    Resharper will give you a big red squiggly – Dave Bish Apr 08 '15 at 14:51
  • have better code review process as well as develop some internal coding best practices. also encourage your coders as well as your self to debug your code and to not check in code that has compiler warnings ... that's a good place to start I would think – MethodMan Apr 08 '15 at 14:55
  • Project properties/Build/Treat warnings as errors/Specific warnings (or better All) – Anton Savin Apr 08 '15 at 14:56
  • +1 for ReSharper. In our team, you are not allowed to submit your code if there are any reSharper warnings. The code review would get rejected. – Andrey Apr 08 '15 at 15:09
  • @DaveBish: Unfortunately, Resharper severity on this by default is set to Warning and not Error, so I didn't catch it. – vinayvasyani Apr 08 '15 at 17:18

1 Answers1

2

Answer for Question 1. Yes

You have to enable 'treat warnings as errors'

  1. Right-click on your project, select "Properties".
  2. Click "Build".
  3. Switch "Treat warnings as errors" from "All" to "Specific warnings" or "None".

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.

Community
  • 1
  • 1
matrixanomaly
  • 6,627
  • 2
  • 35
  • 58