david.pfx david.pfx - 3 months ago 8
C# Question

Is there a way to invoke a templated class on an anonymous type?

Here's some code to give the idea.

public class C<T> { }
public class X {
void M() {
var V = new { W = 1 };
var X = new C<V>(); // illegal
}
}


So V is a variable of an anonymous type and I would like to instantiate class C with V as its argument. This requires a type argument, which I cannot supply.

This questions is similar but the answer is not much help in my case: Why can't I instantiate a generic class inferring types from anonymous objects?

The question behind the question is that I'm trying to do what IEnumerable can do.




Should have made it clear: I would really prefer not to do this by manipulating
object
or
Type
because you lose the benefits of strong typing and Intellisense.




For anyone interested, the project that needs this is described here: http://www.andl.org/2016/07/andl-net-making-progress/.

Jon Jon
Answer

You can use type inference if you have a factory method:

public class C<T>
{
    public C(T t)
    {
        // ...
    }
}

public static class Factory
{
    public static C<T> Create<T>(T t)
    {
        return new C<T>(t);
    }
}

public class Thing
{
    void Foo()
    {
        var x = new { y = "z" };
        //var thing = new C(x); - doesn't work, you need to specify the generic parameter
        var thing = Factory.Create(x); // T is inferred here
    }
}
Comments