Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically add a field to a class in C#

Tags:

Is there any way to add Field (or FieldInfo, maybe this is the same) to a class at runtime?

like image 427
Pavel Podlipensky Avatar asked Mar 14 '09 17:03

Pavel Podlipensky


2 Answers

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.

like image 122
mmx Avatar answered Sep 19 '22 22:09

mmx


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.

like image 33
JaredPar Avatar answered Sep 19 '22 22:09

JaredPar