In my reflective C# code I iterate over the methods on an interface and emit a class that a) is declared as implementing the interface b) has all the methods implemented that GetMethods()
returns.
var methods = typeof(T).GetMethods(); // T is interface
foreach (var methodInfo in methods)
{
var parameters = methodInfo.GetParameters().Select(p => p.ParameterType).ToArray();
var method = typeBuilder.DefineMethod(
methodInfo.Name,
MethodAttributes.Public | MethodAttributes.Virtual,
methodInfo.ReturnType,
parameters);
... // Emit IL
This creates not only the methods but also the properties and events as pairs of methods (get_ set_ / add_ remove_).
The dynamically created class is accepted by the CLR as an implementation of the interface and calling the properties and events on the object (cast as interface) works fine. However in the type builder there is DefineProperty
as well as DefineMethod
. Using ildasm I can confirm that '.property' is missing from the declaration if just using DefineMethod
. Is it naughty to implement an interface's properties and events as if they were 'just' methods? Or is this completely legitimate?
Is it naughty to implement an interface's properties and events as if they were 'just' methods?
Yes, it is. You won't be able to use properties as properties (when using dynamic
).