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?