Last active
August 29, 2015 14:00
-
-
Save dchw/f8220a95cdf056d01bca to your computer and use it in GitHub Desktop.
An extension method to enamble casting by example in C#.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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