Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# and Interfaces - Explicit vs. Implicit

In C#, if a class has all the correct methods/signatures for an Interface, but doesn't explicitly implement it like:

class foo : IDoo {}

Can the class still be cast as that interface?

like image 470
Jason Wicker Avatar asked Apr 24 '09 20:04

Jason Wicker


2 Answers

Duck Typing

What you are alluding to is referred to as "duck-typing" (named after the idiom "if it looks like a duck, and quacks like a duck, then it must be a duck").

With duck-typing an interface implementation is implicit once you have implemented the relevant members (just as you describe) however .NET does not currently have any broad support for this.

With the emergent dynamic language features planned for the future, I wouldn't be surprised if this were supported natively by the runtime in the near future.

In the mean time, you can synthesise duck-typing via reflection, with a library such as this, which would allow you to do a duck-typed cast like this: IDoo myDoo = DuckTyping.Cast<IDoo>(myFoo)

Some Trivia

Interestingly, there is one small place where duck-typing is in use in C# today — the foreach operator. Krzysztof Cwalina states that in order to be enumerable by the foreach operator, a class must:

Provide a public method GetEnumerator that takes no parameters and returns a type that has two members: a) a method MoveMext that takes no parameters and return a Boolean, and b) a property Current with a getter that returns an Object.

Notice that he makes no mention of IEnumerable nor IEnumerator. Although it is common to implement these interfaces when creating an enumerable class, if you were to drop the interfaces but leave the implementation, your class would still be enumerable by foreach. Voila! Duck-typing! (Example code here.)

like image 62
Daniel Fortunov Avatar answered Sep 23 '22 13:09

Daniel Fortunov


No, it's not like Objective-C and some other languages. You should explicitly declare interface implementation.

like image 21
mmx Avatar answered Sep 20 '22 13:09

mmx