I have a class that used to have a string return type. Now I find I need to return more than a string. I was thinking to return something like below:
public string Test()
{
return ( new { ID = 5, Name= "Dave" } );
}
Is this even possible and if so then what would be the return type? I know it’s not string ..
The object that you return does have a class, but it’s anonymous so you can’t specify it in the code. You just have to return it as an
objectreference:Note that the anonymous type is unknown outside the scope of the method, so reflection is the only way to access its properties.
If you want to be able to use the returned object conveniently, you should declare a class:
Another alternative is to use an existing class, if it fits your purpose. A
KeyValuePairis close to what you use, but then the properties will of course be namedKeyandValueinstead ofIDandName: