Damian Hickey

Mostly software and .NET related. Mostly.

An async await anti-pattern - awaiting tasks instead of just returning them.

I've seen this sort of thing being written, especially by people who are new to the async/await features of C#5/.NET4.5, when delegating to an async method, from an async method:

public async Task FooAsync()
{
    await _m.BarAsync();
}

Instead, they should just be writing:

public Task FooAsync()
{
    return _m.BarAsync();
}

The reason is because, in the former, the C# compiler will create a state machine (as viewed with DotPeek), which is simply unnecessary:

The C# compiler is not smart enough to optimize this out.

Edit: Don't do this either, for the reasons stated above:

public async Task<ActionResult> Index()
{ 
    return await Task.FromResult<ActionResult>(View());
}

This should be written as:

public Task<ActionResult> Index()
{ 
    return Task.FromResult<ActionResult>(View());
}

(Thx to @tourismgeek)

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"));
    }
}