Suppress compiler warnings from your code

You can hide compiler warnings by adding some key words to your class.

Ok, there are very few situations when you would want to do this. Some argue that it should never be done and no code should have warnings. However, if you are really sure then you can use the following.

In my example I have a class that overrides the Equals method but not the GetHashCode method. There is no way of returning a correct hash code in this situation and overriding it and calling the base would suggest the class takes responsibility for that being correct.

So the compiler throws up this warning:

warning CS0659: SPListItemChange' overrides Object.Equals(object o) but does not override Object.GetHashCode()

Fair enough.

In my class definition I can add the following:

#pragma warning disable 0659 //override Equals but not GetHashCode
public class SPListItemChange

{

A short compile later 0 warnings.

Comments

# re: Suppress compiler warnings from your code
Gravatar I assume you're never going to store your object in a Dictionary / Hashtable or anything similar? And I assume that *all* users of your object (present or future) also know not to do that?

I'd suggest that you should implement GetHashCode(), but if you are unable to return a suitable value then you throw a NotImplementedException. This way, at least folk won't delve into the realms of undefined behaviour should they ever stick an instance of your object into a Dictionary.
Left by Steve Strong on 10/3/2008 8:48 AM
# re: Suppress compiler warnings from your code
Gravatar Correct, the object is never designed to be used in a HashTable. The comments in the summary block of the class reflects this. I did consider throwing an Exception in GetHashCode but did not know if the CLR calls this at 'random' points and would cause runtime exception.
Left by Neil Jenman on 10/3/2008 8:53 AM

Leave Your Comment

Title*
Name*
Email (never displayed)
 (will show your gravatar)
Url
Comment*

Please add 8 and 1 and type the answer here:

Preview Your Comment.