“Whatever doesn’t kill you makes you stronger”

That’s how I feel about Code Analysis. It’s painful, but in the end, it teaches me stuff that I didn’t know or hadn’t thought about.

Richard Broida challenged me to see if I could rework some WIN32 P/Invoke code to get it to pass Code Analysis rules. My initial response was pretty close to whining, but I recovered from my temper tantrum and did some investigation.

Luckily, I didn’t have to look too far… The info on the rule “CA1060:MovePInvokesToNativeMethodsClass” provided some useful guidance and explanation.

So I created a class in my project called “NativeMethods” and moved my WIN32 stuff inside of that, including my constants, structs and extern methods. I reworked the code a bit so that I had a .NET friendly “wrapper” around the native methods. Problem solved!

My takeaways:

  1. A static class named NativeMethods, SafeNativeMethods, or UnsafeNativeMethods is treated (at least somewhat) special by the .NET framework or tooling. I haven’t found anything describing the specifics yet, but it’s at least a convention to follow.

  2. The Code Analysis rule explanations are quite useful in learning how to create good quality software that makes appropriate use of the .NET framework.

Cheers!