Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Makes an anonymous type implement an interface
//uses ClaySharp: http://clay.codeplex.com
//add the following usings
//using ClaySharp;
//using ClaySharp.Behaviors;
void Main()
{
var foo = TypeMe<IFoo>(new { Id = 1, Name = "Aaron" });
Console.WriteLine(foo.Id);
Console.WriteLine(foo.Name);
}
// Define other methods and classes here
public interface IFoo {
int Id { get; set; }
string Name { get; set; }
}
public static T TypeMe<T>(object o) {
dynamic clay = new Clay(new PropBehavior(), new InterfaceProxyBehavior());
T v = clay;
var properties = o.GetType().GetProperties();
foreach(var p in properties) {
var x = v.GetType().GetProperty(p.Name);
if(x != null) {
x.SetValue(v, p.GetValue(o, null), null);
}
}
return v;
}
public static T As<T>(this object o) {
return TypeMe<T>(o);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment