Jerry Nixon
Jerry Nixon

Reputation: 31813

Determine if a Class implements an Interface without referencing it

I feel like this should be very possible.

I have an interface, let's call it IJerry. Now, I have a class in variable x. That class implements IJerry perfectly. The thing is, that class does not ever reference IJerry. It just happens to have a perfect, compliant signature with IJerry.

Make sense? Let's say you create a class called MyClass that implements INotifyPropertyChanged. Then you delete the MyClass : INotifyPropertyChanged declaration from the class but you LEAVE the implementation inside the class.

Is there a way to determine if the class "implements" an interface even if it does not make an explicit reference to it?

Upvotes: 3

Views: 204

Answers (3)

bmm6o
bmm6o

Reputation: 6505

You would have to use reflection to see if x had methods that matched the ones on IJerry. The real question is, what are you going to do with the answer? Prior to version 4, C# doesn't support "duck typing", so in order to use your class where an IJerry is required you have to write adapter code.

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941347

There's a lot more to implementing an interface than meets the eye. For one, implementation methods are virtual, even though you don't use that keyword. In fact, you're not allowed to use that keyword. For another, the compiler rearranges the methods to match the method table layout of the interface. Removing the inherited interface from the declaration is guaranteed to make the result incompatible. The methods won't be virtual anymore.

What you are pursuing is called 'dynamic dispatch'. Implemented in the DLR and integrated into .NET 4.0 and the C# 4.0 language. Re-inventing the System.Reflection code and making it efficient is a major undertaking.

Upvotes: 2

James Curran
James Curran

Reputation: 103495

Not easily.

You would have to read the fields, method, and properties of the interface using reflection, and then check if the class has them (again using reflection)

Alternately, if you are using C#4, you could just forget about IJerry, and put MyClass in a dynamic variable, and then you C# figure out at run-time for it has the methods being called.

Upvotes: 7

Related Questions