A C++ style bug in C# or I can't believe this is not a warning

1    21 Sep 2016 09:22 by u/rwbj

I just had this come up. This was 'fun' to track down.

    public async Task<SomeType> GetSomethingAsync()
    {
        await Task.Delay(10); // just to get rid of the async method does not await anything warning for anybody testing this
        return null;
    }
    public void SomeOtherFunction()
    {
        if (GetSomethingAsync() == null)
            DoSomethingIfNotFound();
        else
            DoSomethingElse();
    }

No warning about an asynchronous call not being awaited awaited, unreachable code / redundant tests, or anything. It happily compiles and executes without warning or error. Reminds me a lot of an if( a = b ) bug in C++ if not even nastier. If you don't see the bug, the return type of GetSomethingAsync is a task, not a SomeType. But both can be compared to null. So this test will never get a null since GetSomethingAsync() willl always return a non-null Task who's Result may or may not be null, but always would be in this sample code. Consequently DoSomethingElse() is executed 100% of the time even though you'd expect DoSomethingIfNotFound to be executed 100% of the time. The fix is simply to convert SomeOtherFunction to an async method and await GetSomethingAsync() or change the test to GetSomethingAnsync().Result == null.

Now I'm paranoid I might have missed this elsewhere...

3 comments

1

Buy Resharper by Jet Brains, you'll thank me later. It actually gives a warning that you did not await the call to GetSomethingAsync(). As far as comparison to null, I'm not sure if it'll warn for that. It'll give you all sorts of other warnings and hints showing all the flaws in your code that you never knew you had. Nobody should be developing C# without it.

0

Yeah I was also looking into that before just for precise refactoring of namespaces, which visual studio inexplicably does not support. Only problem is I just abhor the software as a service model.

0

It does so much more than that too. It is, hands down, the best code beautifier/formatter in existence. After getting used to developing with it, I'm hooked. Whenever I switch to a machine without it, I'm like WTF is going on here? Oh yeah, R# isn't installed on this machine.

Yeah, the subscription model sucks. I just checked their page and it's $300 for the first year. I guess it depends if you're just coding for kicks or if this is your business. If it's the latter, I'd recommend sucking it up and buying it for at least one year. If you're just learning/tinkering with C# then it's hard to justify that much money.