It seems like the C# compiler infers types differently depending on how a method is called:
void Foo<T>() where T : Bar
{
var instance = new T()
{
ID = 1
}.
ExtensionMethod();
}
In this case the compiler seems to infer that the type of instance is Bar, because I have a class Bar where ExtensionMethod is declared.
void Foo<T>() where T : Bar
{
var instance = new T()
{
ID = 1
};
instance.ExtensionMethod();
}
In this case the compiler infers that the type of instance is T, which is what I would expect it to do in the first case as well.
Why is there such a difference?
In the first case, you assign the result of the method call to instance. In the second case you discard the call’s result. Instead, you assign the
new TThis is the only difference.