Skip to content

Instantly share code, notes, and snippets.

@aaronpowell
Created December 3, 2010 02:52
Show Gist options
  • Save aaronpowell/726511 to your computer and use it in GitHub Desktop.
Save aaronpowell/726511 to your computer and use it in GitHub Desktop.
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