Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Removing Warnings from CSharp Compile Cycle

DZone's Guide to

Removing Warnings from CSharp Compile Cycle

·
Free Resource
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.

 

Topics:

Published at DZone with permission of Dave Bush, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}