Skip to content

Instantly share code, notes, and snippets.

@dchw
Last active August 29, 2015 14:00
Show Gist options
  • Save dchw/f8220a95cdf056d01bca to your computer and use it in GitHub Desktop.
Save dchw/f8220a95cdf056d01bca to your computer and use it in GitHub Desktop.
An extension method to enamble casting by example in C#.
public static class ObjectExtensions
{
public static T CastByExample<T>(this object o, T example)
{
return (T) o;
}
}
void Main()
{
var anonymousObject = Mystery.Enigma();
var unAnonymousObject = anonymousObject.CastByExample(new
{
Message = String.Empty,
Fruit = String.Empty,
});
Console.WriteLine(unAnonymousObject.Message);
Console.WriteLine(unAnonymousObject.Fruit);
}
public class Mystery
{
public static object Enigma()
{
return new
{
Message = "Anonymous type!",
Fruit = "Mango"
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment