简体   繁体   中英

C# compiler type inference difference between inline method call and separate method call

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 T This is the only difference.

According to the var keyword definition in Implicitly Typed Local Variables :

The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement

On the right side of the var ,in your case, there is not only the ctor part, but also a function call, which returns void. So it turns out in infering the type assignable to var from void returned by the function call. This leads to a compiler signal about a fact:

Cannot assign void to an implicitly-typed local variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM