Consider this code:
using System;
class EntryPoint{
static void Main(){
f(new{ Name = "amir", Age = 24 });
}
static void f <T> (T arg){}
}
This code compiles with C# 9 compiler. I can send anonymous type where a generic type is expected. My question is why I can't do the same for method return types?
For example, consider this code:
using System;
class EntryPoint{
static void Main(){
object obj = f();
}
static T f <T> (){
return new{ Name = "amir", Age = 24 };
}
}
It will get the following compile errors:
main.cs(6,22): error CS0411: The type arguments for method 'EntryPoint.f()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
main.cs(10,16): error CS0029: Cannot implicitly convert type '<anonymous type: string Name, int Age>' to 'T'
Why these same errors do not appear in the other code. In the other code the anonymous type is also implicitly converted to T. Why this can't happen here?
Thanks in advance for helping me!
Anonymous types are just types that the C# compiler defines for you. So lets change your example to use concrete types;
Now it should be obvious in the second example, that types
TandFooare not the same.