Created
March 19, 2009 04:42
-
-
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.
This file contains 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
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