views:

51

answers:

2

After reviewing this blog by Kirill Osenkov (How to create a generic List of anonymous types?) I am trying to do something a little more advanced and having issues.

The following code compiles:

    var anon = new { One = "1", Two = "2" };
    var result = DoSomething(anon);

    public static T DoSomething<T>(T value)
    {
        return value;
    }

But if I try to add an additonal generic type, I cannot get it to build:

    var anon = new { One = "1", Two = "2" };
    var result = DoSomethingElse<int>(anon);

    public static T2 DoSomethingElse<T, T2>(T value)
        where T2 : new()
    {
        return new T2();
    }

Since I have no way of specifiying that T is typeof(anon), I can't seem to get it to infer this when given a type for T2. Is this possible?

+2  A: 

No. This type of feature is not supported by the C# compiler. You must either manually specify all generic parameters or none and rely on type inference.

The closest you'll get is the following

var anon = new { One = "1", Two = "2" };
var result = DoSomethingElse(anon,42);

public static T2 DoSomethingElse<T, T2>(T value, T2 otherValue)
    where T2 : new()
{
    return new T2();
}
JaredPar
A: 

Not really a satisfying answer, but you could do the following, if you can tolerate writing a different version of DoSomethingWithT2 for each type T2:

var anon = new { One = "1", Two = "2" };
var result = DoSomethingWithInt(anon);

public static int DoSomethingWithInt<T>(T value)
{
    return DoSomethingElse<T, int>(value);
}

public static T2 DoSomethingElse<T, T2>(T value) where T2 : new()
{
    return new T2();
}

The correct-est answer is just to stop using an anonymous type here and use a tuple or define your own type. Sorry.

mquander