Hi,
Is there any way to add Field (or FieldInfo, maybe this is the same) to the class in runtime?
Thanks, Paul.
Hi,
Is there any way to add Field (or FieldInfo, maybe this is the same) to the class in runtime?
Thanks, Paul.
No, C# doesn't allow monkey-patching.
You can generate new classes using either CodeDOM or Reflection.Emit, but you can't modify existing ones.
You can't alter a class definition at runtime. However, you can create a new class that inherits from the original class (if it's not sealed
) and declares the field. You can do this by emitting the appropriate IL code using System.Reflection.Emit
.
Not exactly.
However, you can implement ICustomTypeDescriptor to approximate it, and then just use a hashtable to store the fieldname/value pairs. A lot of the framework which uses reflection asks for ICustomTypeDescriptor first.
Not until C# 4.0 which adds dynamic lookup and is based on the CLR 4.0 which incorporates the DLR, and then it will not strictly be adding to a class, as classes won't be in the picture.
C# does not allow it because all of it's classes are based on Metadata. The CLR (not C#) disallows the adding of fields to metadata at runtime (1). This is the only way that C# would be able to add a field at runitme.
This is unlike dynamic langauges such as IronPython which essentially don't have concrete metadata classes. They have more dynamic structures which can be altereted at runtime. I believe IronPython simply keeps it's members (fields and methods) in what amounts to a hashtable that can be easily altered at runtime.
In C# 3.0, your best resource is to use Reflection.Emit. But this will generate an entirely new class vs. altering an existing one.
(1) There are certain APIs such as the profiling APIs or ENC that allow this but I'm not sure if their capabalities expand to adding fields.
Hi, as others already said, this isn't possible. What is the reason for your question? If you need to store some additional data in the class dynamically, then you could probably just use dictionary:
class My {
Dictionary<string, object> data;
public My() { data = new Dictionary<string, object>(); }
}
.. but it really depends on what you actually want to achieve?