简体   繁体   中英

why I can't return anonymous type as generic in C#, while I can do the same for method parameters?

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;

public class Foo {
    public string Name { get; set; }
    public int Age { get; set; }
}

static void Main(){
    f1(new Foo{ Name = "amir", Age = 24 });
}

static void f1<T> (T arg){}

static T f2<T> (){
    return new Foo{ Name = "amir", Age = 24 };
}

Now it should be obvious in the second example, that types T and Foo are not the same.

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