Reputation: 20050
I'm using types from the Reflection.Emit
namespace for generating a dynamic assembly on the fly (with dynamic types in it).
Both Reflection and the Reflection.Emit
namespace provide APIs for dealing with methods and properties of CLR types.
To my knowledge, properties are implemented as methods by the C# compiler, and so i'm wondering how should these be treated when emitting them dynamically?
Should Properties be emitted by using a MethodBuilder
or using a PropertyBuilder
? (i.e: by calling DefineMethod
or DefineProperty
?)
Is there any recommendation for one approach over the other?
Upvotes: 2
Views: 171
Reputation: 244837
Should properties be emitted by using a
MethodBuilder
or using aPropertyBuilder
?
Both. If you have a read-write property X
, then in CIL it's represented as a a get method (usually called get_X
), a set method (usually called set_X
) and a properly called X
that points to the two methods.
So, to create a property using Reflection.Emit, you should:
MethodBuilder
to create the get method (probably reading from some field).MethodBuilder
to create the set method (probably writing to the same field).PropertyBuilder
to create the property, setting its Name
and calling SetGetMethod()
and SetSetMethod()
.If you want to create a read-only property, just skip step 2 and don't call GetSetMethod()
.
Upvotes: 4