简体   繁体   中英

Visual Studio convert Compilation Warning into Build Error

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM