Question

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?

Was it helpful?

Solution

Should properties be emitted by using a MethodBuilder or using a PropertyBuilder?

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:

  1. Use MethodBuilder to create the get method (probably reading from some field).
  2. Use another MethodBuilder to create the set method (probably writing to the same field).
  3. Use 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().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top