I am trying to make an anonymous object an 'out' parameter.
This code compiles:
public T GenericTest<T>(T Input)
{
return Input;
}
public void AnonymousObjectTest()
{
var AnonObj = new { Prop = "hello" };
var Str = GenericTest(AnonObj).Prop;
Console.WriteLine(Str); //outputs "hello" to the console
}
However, how can I get this to work? See the following. I am trying to use an anonymous object as an 'out' parameter for the method "OutParamTest".
Honestly, it shouldn't be any different than returning generic type T, since the method's output type is declared to be the same as the input. But yet, I don't know of which type to use other than 'object' in the method call:
public void OutParamTest<T>(T Input, out T Output)
{
Output = Input;
}
public void AnonymousObjectTest()
{
var AnonObj = new { Prop = "hello" };
OutParamTest(AnonObj, out object Test); //how can I make the 'out' parameter type the same as the 'input' parameter?
var Str = Test.Prop; //CS1061: 'object' does not contain a definition for 'Prop'
Console.WriteLine(Str);
}
You can:
var obj = new { A = 1 };
OutParamTest(obj, out var obj2);
using the var
that was introduced in C# 3.0 exactly for anonymous types, and that from C# 7.0 can be put inline with out
.
On older C# compilers you can also:
var obj = new { A = 1 };
var obj2 = obj;
OutParamTest(obj, out obj2);
(being an anonymous type a reference type, the var obj2 = obj
is inexpensive)