Robin
Robin

Reputation: 737

In .NET IL is it acceptable to implement an interface's properties and events directly as methods?

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?

Upvotes: 4

Views: 154

Answers (2)

Mike Nakis
Mike Nakis

Reputation: 61993

It is naughty, and you do not want to do this.

If you do this, your objects may be fine from the point of view of other code invoking them, but they will not be complete from the point of view of reflection. So, your objects will not behave correctly in any situation where proper reflection information is required.

As another answer states, Dynamic is an example of such a situation.

<off-topic>

I do not care about Dynamic at all. Dynamic is:

  • a workaround for bad designs, and

  • its use leads to irrevocably worse designs.

I understand Dynamic is almost everyone's darling nowadays. That's because nowadays almost everyone is a script kiddie.

</off-topic>

 

But here is a worse problem:

If you try to view your objects in the "Locals" or "Autos" window of the Visual Studio debugger, your generated properties will not appear! The Visual Studio debugger enumerates the properties of an object in order to decide what to show there, so if your object does not properly define its properties, they will not be shown.

I just encountered this problem with my own stuff and wrote a Question-and-Answer about it:

Emitted properties do not appear in the debugger

Upvotes: 2

mjwills
mjwills

Reputation: 23898

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).

Upvotes: 4

Related Questions