13

Why isn't it possible to cast an instance of:

sealed class Foo
{
    public void Go() { }
}

...to this interface:

interface IBar
{
    void Go();
}

...even though Foo has the signature of IBar?

How can I turn an instance of Foo into an IBar? Assume I have no control over Foo.

2
  • 2
    "Assume I have no control over Foo" Then it's not an IBar and you can't cast it. You could wrap it in a different clas that does implement IBar but you can't cast it.
    – D Stanley
    Sep 30, 2016 at 2:32
  • This is called structural typing and some languages do in fact support this - TypeScript to name one which was designed by some of the same people. Sep 30, 2016 at 9:05

4 Answers 4

25

No, C# does not support duck-typing.

The OOP-approach to this problem is to use the Adapter Pattern.

You would do this:

class FooBarAdapter : IBar {

    private readonly Foo foo;

    public FooBarAdapter(Foo foo) {

        this.foo = foo;
    }

    public void Go() {

        this.foo.Go();
    }
}

Whenever you have a Foo but need an IBar you wrap it on-demand:

public void ContrivedScenario() {

    Foo foo = GetFooFromExternalDependency();

    FooBarAdapter adapter = new FooBarAdapter( foo );

    this.NeedsIBar( adapter );
}

public void NeedsIBar(IBar bar) { ... }

I note that if Foo-to-IBar conversion happens a lot, you can make use of implicit conversions, so you don't need to explicitly construct FooBarAdapter instances, but it is debatable if this is good software engineering practice or not:

class FooBarAdapter : IBar {

    // (same as above)

    public static implicit operator FooBarAdapter(Foo foo) {
        return new FooBarAdapter( foo );
    }
}

That way you can do this:

public void ContrivedScenario() {

    Foo foo = GetFooFromExternalDependency();

    this.NeedsIBar( foo ); // the conversion from `Foo foo` to `FooBarAdapter` happens implicitly
}

One reason why C# doesn't support duck-typing is because just because a class's interface (in the OOP sense, not a literal interface) shares the same identifiers as another, doesn't mean they're compatible. For example Process.Kill (kills the process) and MegaDeathKillBot3000.Kill (kills all humanity) probably shouldn't be used interchangeably... unless you really want to.

1
  • 1
    An excellent answer but I would like to thank you particularly for the MegaDeathKillBot3000 example. Or really just for the existence of MegaDeathKillBot3000. :)
    – Chris
    Sep 30, 2016 at 10:21
3

In addition to @Dai's answer, an alternative is using a mock framework, if you want to do your foo-bar cast in a test project.

var bar = Mock.Of<IBar>();
Mock.Get(bar).Setup(b => b.Go()).Callback(() => foo.Go());

MethodThatNeedsIBar(bar);

The framework creates a proxy of type IBar to foo, working like an adapter, but it's easier to setup and less code.

3

C# doesn't have "duck typing". In order for you to cast an instance from one type to another, they must have an inheritance relationship or have a custom cast overload defined. In this case though, you could have create a simple subclass for Foo like this if Foo weren't sealed:

class SubFoo : Foo, IBar {
    void Go()
    {
        base.Go();
    }
}

But since Foo itself is sealed, this is not possible, so instead you have to use containment like this.

class ContainsFoo : IBar 
{
     ContainsFoo(Foo foo)
     {
         this.foo = foo;
     }

     void Go() 
     {
         this.foo.Go();
     }
}
1

There is also the Impromptu-Interface package which handles the wrapped duck-typing for you. It's a well established framework with multiple options including the ability to handle collections.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.