Supressing warnings in C#


I’ve been trying to be a good little programmer and eat all my errors and warnings whenever mamma-compiler puts them on my plate.  But sometimes I don’t know what to do with the warnings I get.  For example, I sometimes declare a try-catch block where the catch consumes the exception without re-throwing.

MyObject mo;
try
{
    mo = new MyObject(flakyConstructorParm);
}
catch (Exception ex)
{
    mo = null; // error has been handled, no throw needed.
}

The problem with this is that the compiler will complain that ex is declared but never used. I know that I could declare the catch as

catch (Exception)

since I am not referencing the exception, but I find it is nice to see the value in ex while debugging, so I try to make it a standard practice to declare an actual variable for the exception in all catch blocks.

The solution to this is to use a #pragma to suppress the compiler warning:

MyObject mo;
#pragma warning disable 0168
try
{
    mo = new MyObject(flakyConstructorParm);
}
catch (Exception ex)
{
    mo = null;
}
#pragma warning restore 0168

So where did I get the number 0168? Look at the warning as displayed in the Output window; you’ll see the number displayed with a prefix of “CS”.  You can add other warnings by separating the numbers with commas.
You can read more about this here.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s