VS Code incorrectly infers types from extension methods

Viewed 21

I have an extension method with an out argument, like this:

public static class BinaryDataExtensions 
{
    public static bool ParseSomething<T>(this BinaryData data, out T? parsed) : where T : new() 
    {
        parsed = default;
        // Try to parse data
        return /*did we succeed?*/;
    }
}

When I use it with an in-line declared var, like this:

BinaryData data;

if (data.ParseSomething<Dictionary<string, string>>(out var this_should_be_a_dict))
{
    // use this_should_be_a_dict
}

VS Code frequently decides that this_should_be_a_dict is in fact BinaryData.

Doing the same with an extension method for string makes VS Code decide that it's a string.

This does not cause any problems, so the problem is not with the extension method:

data.ParseSomething<Dictionary<string, string>>(out Dictionary<string, string> actually_a_dict)

Specifying the type explicitly works, but that's rather a lot of typing, and this should be simple enough. It looks to me like the the type inferencer has an off-by-one error in the argument indexes when it comes to extension methods.

This question seems to be related: Intellisense cannot infer type from extension method

Is there anything I'm missing here that will allow me to avoid typing the output type twice every time?

1 Answers

You only need to specify the generic type of a method if it can't be inferred from the parameters. If you specify the type of the parameter then it can be inferred, so you don't need to specify it twice:

BinaryData data;
if(data.ParseSomething(out Dictionary<string, string> this_should_be_a_dict)){
    // use this_should_be_a_dict
}
Related