Getting value from anonymous type?

anonymous-types, c#

Solution

Note that returning anonymous types or `Tuple<>` from a method is a bad thing to do

But you asked a question about how to do it, not about "is it a good idea"...

By using dynamic or reflection...

dynamic b = Test();
string str = b.A;

Or by cheating:

public static object Test()
{
    return new { A = "Test" };
}

public static string GetA(object obj)
{
    // We create an anonymous type of the same type of the one in Test()
    // just to have its type.
    var x = new { A = string.Empty };

    // We pass it to Cast, that will take its T from the type of x
    // and that will return obj casted to the type of the anonymous
    // type
    x = Cast(x, obj);

    // Now in x we have obj, but strongly typed. So x.A is the value we
    // want
    return x.A;
}

public static T Cast<T>(T type, object obj) where T : class
{
    return (T)obj;
}

string str = GetA(Test());

In C# all the anonymous types with the same properties of the same type that are in the same assembly are merged together. So the `new { A }` of `Test()` and of `GetA()` are of the same type.

The `Cast<T>` is a useful trick to extract the type from an anonymous type. You pass as the first parameter your typed anonymous type (the parameter is used only to "activate" the generic `T`) and as the second parameter the object you want to cast. Similar tricks can be used to create collections of generic types, like

public static T MakeList<T>(T type)
{
    return new List<T>();
}

Problem

Let's say we've got the following method: ``` public object Test() { return new { A = "Test" }; } ``` Is there a chance of getting the value that is stored in A? ``` var b = Test(); //Any chance to cast this to the anonymous type? ```

Original source

Related problems