Friday, June 13, 2008

Making Anonymous Types Read-Write

Tried creating anonymous types and changing its value ?? Its strange, but Anonymous types in C# are readonly.

var v = new { FName = "aaa" , LName = "bbb" };
v.FName = "aaaa";


Above lines of code would yield following error

"Property or indexer 'AnonymousType#1.FName' cannot be assigned to -- it is read only"

But ofcourse, there is a workaround, you can use reflection to change the value of the Anonymous Method.

Type t = v.GetType();
FieldInfo fi = t.GetField( "i__Field" , BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(v, "1234");


i__Field is the internal name used for refering to property "FName". Fire up ildasm to get it.

Its true that the power of reflection cannot be ignored no matter what new features are added to .Net framework.