Jason Wicker
Jason Wicker

Reputation: 3456

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?

Upvotes: 10

Views: 938

Answers (5)

Daniel Fortunov
Daniel Fortunov

Reputation: 44333

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

Upvotes: 17

Reed Copsey
Reed Copsey

Reputation: 564413

This would basically require Duck Typing to work in C#, which does not happen automatically.

There are some libraries that can do this, though.

Upvotes: 3

ecoffey
ecoffey

Reputation: 3663

public class A
{
   public void DoSomething();
}

public interface IDoSomething
{
   void DoSomething();
}

public class B : A, IDoSomething
{ }

B satisfies IDoSomething.DoSomething by inheriting from A

Upvotes: 2

BnWasteland
BnWasteland

Reputation: 2119

Provided that IDoo has any members, this code won't compile. If IDoo has no members, then yes, the cast is safe (but obviously of limited use).

Upvotes: 4

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421988

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

Upvotes: 12

Related Questions