Monday, July 12, 2010

You Can Actually Cast To Anonymous Types

Just a quick note, one can really cast to anonymous types!

There's a very interesting quote in the C# specifications regarding anonymous types:

"Within the same program, two anonymous object initializers that specify a sequence of properties of the same names and types in the same order will produce instances of the same anonymous type"


This means this:
var x = new { Name = "Jon Doe", Position = "Manager" };

and this:
var y = new { Name = "Chuck Norris", Position = "The One" };

will produce instances of the same type, hence x.GetType() and y.GetType() will yield the same result.
Now how to cast? For example, if you have a method like the following:

object Test() { 
return new { Name = "XYZ", Position = "ABC" };
}

One way to cast the return of this method is as follows:
var ret = Test();
var retCasted  = Cast(ret, new { Name = "", Position=""});
Console.WriteLine("Name: {0} -- Position: {1}"retCasted.Name, retCasted.Id);

Here's my Cast method:
T Cast<T>(object o, T type)
{
  return (T)o;
}

OK, just that quick tip!

No comments: