Skip to content

Instantly share code, notes, and snippets.

@brendanjerwin
Created March 19, 2009 04:42
Show Gist options
  • Save brendanjerwin/81598 to your computer and use it in GitHub Desktop.
Save brendanjerwin/81598 to your computer and use it in GitHub Desktop.
An example of a neat trick to get a generic to work with an anonymous type.
using System;
namespace TestAnonymousGeneric
{
internal class MyClass<T>
{
public T val { get; set;}
public static MyClass<ET> Build<ET>(ET valValue)
{
return new MyClass<ET> {val = valValue};
}
}
internal class MoreComplex
{
public string foo { get; set; }
}
class Program
{
static void Main(string[] args)
{
//The "<int>" isn't really meaningful, the type used here doesn't matter. I use "int" since it's short.
var foo = MyClass<int>.Build(new {Name="This is a Name", Count=1, Com=new MoreComplex()});
//foo.val.Name = "Can't write to this. It's read only.";
Console.WriteLine(foo.val.Name);
foo.val.Com.foo = "This is writable";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment