Can I change the field of a class at runtime in c#?
for example, if i have the class:
public class ExampleClass{
public string Name;
}
can I Change it at runtime, using reflection or other techniques, to change the Name to Name1?
public class ExampleClass{
public string Name1;
}
Have a look at DynamicObject:
http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx
No, you cannot change the actual members of a type at runtime
Options:
ExampleClass
, but has different members - and presumably some mapping code between themICustomTypeDescriptor
orIDynamicMetaObjectProvider
- which will allow some frameworks to treat it as though it had aName1
, even though it actually doesn't (note: things likeDynamicObject
andExpandoObject
include implementations ofIDynamicMetaObjectProvider
, but you can do it in other ways)var val = obj["Name1"];
returns something meaningful