Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

Dave Bush has been programming for 20 years. He currently blogs about .NET at http://blog.dmbcllc.com and provides .NET coaching to small and medium sized companies. Dave is a DZone MVB and is not an employee of DZone and has posted 33 posts at DZone. You can read more from them at their website. View Full User Profile

Removing Warnings from CSharp Compile Cycle

03.10.2009
Email
Views: 1254
  • submit to reddit
One of the things I try to do when I’m working on my CSharp projects is to make sure I don’t have any compile errors or warnings.  The reason for removing the errors is probably obvious, if you have an error, you code isn’t going to run at that place.  But, what about the warnings?

Well, warnings are there because they are potential errors.  Things you really ought to fix because they could end up causing unexpected results in your program.

So how do we deal with warnings?

The first thing you should do in your code is go through all of your warnings and make sure they aren’t something you couldn’t fix by re-arranging your code.  Most of the warnings that show up in your code are of this type.

But what about warnings that you can’t remove?

This code

int _x = 1;
string s=null;
if(_x is object)
s = "abc";
if (_x != 1)
s = "xyz";
MessageBox.Show(s);

Will produce an error at “if(_x is object)” because value types are always objects.  There is not need to have the if statement.

We should remove the conditional statement or replace it with something more meaningful.  But, let’s suppose that we can’t.  How can we prevent the error from showing up?

By using the #pragma warning directive.

            int _x = 1;
string s=null;
#pragma warning disable 183
if(_x is object)
s = "abc";
#pragma warning restore 183
if (_x != 1)
s = "xyz";
MessageBox.Show(s);

The disable statement will disable a comma separated list of warnings from showing up in your compiler’s warning list.  The restore statement turns them back on.

Unfortunately, the place where I need this feature the most is in some VB.NET code that I’m writing.  Currently this feature is not supported in VB.NET, but there is a rumor that it is to be supported in the 2010 release.

 

References
Published at DZone with permission of Dave Bush, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)