Damian Hickey

Mostly software and .NET related. Mostly.

Extension Methods, Guards Clauses and Code Analysis

´╗┐Code Analysis, when encountering this:

public static class FooExtensions
{
    public static void Bar(this Foo instance)
    {
        Guard.Against(instance != null, () => new ArgumentNullException("instance"));
    }
}

...results in a a warning:

CA2208 : Microsoft.Usage : Method 'FooExtensions.Bar(this Foo)' passes 'instance' as the 'paramName' argument to a 'ArgumentNullException' constructor. Replace this argument with one of the method's parameter names. Note that the provided parameter name should have the exact casing as declared on the method.

The problem here is that the 'this Foo instance' paramater isn't a paramater in the usual sense, so I can't use ArgumentNullException or ArgumentException.

Perhaps NullReference exception then? Nope...

CA2201 : Microsoft.Usage : 'FooExtensions.Bar(this Foo)' creates an exception of type 'NullReferenceException', an exception type that is reserved by the runtime and should never be raised by managed code. If this exception instance might be thrown, use a different exception type.

So I've settled on using InvalidOperationException.

 

public static class FooExtensions
{
    public static void Bar(this Foo instance)
    {
        Guard.Against(instance != null, () => new InvalidOperationException("instance"));
    }
}