Search code examples
c#typescastinganonymous

C# type cast exception for anonymous type, why?


I've got a very simple code snippet:

    public static object ParseData(string s)
    {
        string[] array = s.Split(' ');
        return new { Name = array[0], Address = array[1], Postcode = array[2] };
    }

    static T Cast<T>(object obj, T type)
    {
        return (T)obj;//throws exception!
    }
    public static void Main(string[] args)
    {
        string s = "john, 20st, 100020";
        var o = Cast(ParseData(s), new { Name="", Address="", PostCode="" });
    }

On running, it prints an exception information:

Unhandled Exception: System.InvalidCastException: 
Unable to cast object of type 
'<>f__AnonymousType0`3[System.String,System.String,System.String]'
to type
'<>f__AnonymousType1`3[System.String,System.String,System.String]'.

at ConsoleApp1.Program.Cast[T](Object obj, T type) 

Why is that, how to fix my code?


Solution

  • The types are not concrete. They are the same shape now, but that's a coincidence. I try to only use anonymous types as an intermediary step when building up the data for a concrete class, and the anonymous type rarely leaves the scope of a single method.

    Anonymous types are hard to test, hard to pass around, and as you've found, are hard to convert.

    I sometimes use anonymous types to return data from a web api method, so give the response a specific shape when it serialises to JSON. However the consumer will usually be a JS client and doesnt depend upon a C# type, anonymous or concrete to deserialise the JSON to objects.