SuppressMessage not in CF

Thu, May 5, 2005, 01:52 PM under MobileAndEmbedded
As you may have noticed, in VS2005 you can turn static code analysis on via the project properties ("Enable Code Analysis"). Many of the rules are just guidelines and do not qualify as warnings. There should be a separate category, maybe called *recommendations*. However, that is not the point of this blog post.

Fortunately, you can suppress warnings simply by right clicking on them and choosing "Suppress". What that does is to add an attribute to the line of code that breaks the recommendation so next time you compile/build, the annoying warning will not appear in the error list. The attribute is the System.Diagnostics.CodeAnalysis.SuppressMessageAttribute (it applies only if the compilation constant CODE_ANALYSIS is defined)

Example:
// no comments on the content of the method please
public void SomeMethod(bool b, object o) {
if (b) {
((EventHandler)o).Invoke(null, EventArgs.Empty);
} else {
((EventHandler)o).BeginInvoke(null, EventArgs.Empty, null, null);
}
}
One of the 4 warnings you'll see for the method above is the following:
CA1800 : Microsoft.Performance : 'o', a parameter, is cast to type 'System.EventHandler' multiple times in method Class1.SomeMethod(Boolean, Object):Void. Cache the result of the 'as' operator or direct cast in order to eliminate the redundant castclass instruction.

So, you bring up the contextmenu for the item in the "Error List", select "Suppress message" and life is good again.

So where is the problem? As the title of this entry suggests, the attribute is not supported by the Compact Framework (at least in Beta 2) and doesn't compile:
The type or namespace name 'CodeAnalysis' does not exist in the namespace 'System.Diagnostics' (are you missing an assembly reference?)

There are two issues with that:
1. You cannot suppress those annoying recommendations warnings that shouldn't be there in the first place.
2. If you are sharing code between the full and compact frameworks, you'll get compilation errors.

There is nothing you can do about the 1st one (apart from vote for it).
For the second, as you know, you can use conditional compilation. However, in this case I'd go ahead and define the attribute in code in your CF projects, so at least you get past the compilation problem. Define it like this:
namespace System.Diagnostics.CodeAnalysis {
public class SuppressMessageAttribute : Attribute {
public SuppressMessageAttribute(string category, string checkId) {}
}
}

Note, I tried implementing the attribute fully but the warnings were still not suppressed so the bare minimum skeleton as above is good enough to at least get us past the compilation errors