How to pass an anonymous object to a generic method with multiple generic types?

1.1k Views Asked by At

Let's say I have this generic method:

public T1 GenericTest<T1, T2>(T2 Obj, out T2 NewObj)
{
    NewObj = Obj;
    return default;
}

How do I pass an anonymous object to it?

What do I put in place of the "???" when calling the method in the following example:

var Anonymous = new { Prop1 = "foo", Prop2 = "bar" };
GenericTest<bool,???>(Anonymous, out var NewAnonymous);
NewAnonymous.Prop1 = "Hello";
NewAnonymous.Prop2 = "World";
//etc...

My goal is to have Visual Studio's Intellisense pick up "Prop1" and "Prop2" on the "NewAnonymous" object after I call the method. This requires the anonymous type to be inferred, but I don't know how to do it with multiple type specifiers.

NOTE: I want to be able to access the properties of the anonymous object that is returned from the "out" parameter, so type "object" will not be good enough. If I put "object" as the type, I won't be able to access the properties "Prop1" and "Prop2" on the "NewAnonymous" object from outside the method.

NOTE 2: I do not need to access the properties of the anonymous object from within the method.


EDIT: Anonymous objects can indeed be passed to generic methods. I just don't know how to do it with a generic method with multiple type specifiers (which is why I made this question). Here is an example with just one type specifier:

public void SingleGenericTypeTest<T>(T Obj, out T NewObj)
{
    NewObj = Obj;
}
var Anonymous = new { Prop1 = "foo", Prop2 = "bar" };
SingleGenericTypeTest(Anonymous, out var NewAnonymous);
NewAnonymous.Prop1 = "Hello";
NewAnonymous.Prop2 = "World";
//etc...
1

There are 1 best solutions below

0
On

Type inference requires that all generic types be inferred. If your method took an argument of type T1 you could then elide the types. Unfortunately you can't do that here since no parameter of the first type exists and there's no way to specify the unspeakable anonymous type.

The best you are going to get is a helper method with one generic argument that passes through to the second, specifying both types:

public bool GenericHelper<T>(T Obj, out T NewObj)
{
    return GenericTest<bool, T>(Obj, out NewObj);
}

public T1 GenericTest<T1, T2>(T2 Obj, out T2 NewObj)
{
    NewObj = Obj;
    return default;
}

Which you can then use:

var Anonymous = new { Prop1 = "foo", Prop2 = "bar" };
bool res = GenericHelper(Anonymous, out var NewAnonymous);

Though it still doesn't make much sense that you want to do this.