How to Prevent Future Errors in Your C# Code

Rasheed K Mozaffar - Aug 26 '23 - - Dev Community

Hey There! 👋🏻

Today's post is short and quick, I just wanted to share this small tip with you that I recently learned about, and I think it's a game changer, even though it's only a single line of code, not even in C#, but bare with me, it'll surely help you write more efficient and less error-prone code in your projects.

Let's Get Started 🚀

Since the release of .NET 6, the compiler started giving out warnings of things that it thinks could cause errors and exceptions to be thrown at some point in time, so the compiler would show those warnings, to tell you that, hey, this is some dangerous code right here, do something about it, and when you run a project (That's built with .NET 6 and later.), you would see a bunch of warnings just thrown all over the place, like this:

Compiler warnings in .NET 6 and later

Now your project will still run just fine, but there's a greater likelihood it'll break due to something that's probably mentioned within that pile of warnings, and it happens A LOT, like NullReferenceException and similar exceptions.

What's The Solution? 🔎

There's a compiler setting, that you define inside the .csproj file, which tells the compiler to treat those warnings as errors, yes you heard that right, those warnings you have seen in that screenshot, will all be converted into errors, and if you have like 50+ warnings, then I just recommend staying away from this, because handling 50 errors at once is tough.

To enable this setting, double click the project, that will open the project file, simply add this line:

The fixed version of the compiler setting

⚠️ NOTE: When I first published this post, I had put the value enable for that setting, and that doesn't work, the setting takes either true or false. Sorry for the confusion if it didn't work for you at first!

Why's That Useful? 💡

You might be asking how introducing more errors is something good? Well, firstly, I recommend doing this when you're starting out with a new project, with fresh code, and not couple thousand lines with like 100+ warnings. Secondly, those warnings are originally potential errors, and the compiler is pointing them out for you to ensure that you properly handle them, so when you're forced to fix them, since your project won't even run without doing so, you're ensuring that your code is very less likely to crash due to some exception that was mentioned in the warnings, you'll take the time to properly tune the code so that it won't fail or crash, and therefore making your code more robust, less error-prone, and safe.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .