Oscar
Oscar

Reputation: 13960

Cast object to non explicit implemented interface

It's somehow possible to cast an object to an interface which it doesnt inherit directly? In my sample code below, is there any way to convert an All instance to a Single one?

public interface  IA
{
    void A();
}

public interface IB
{
    void B();
}

public interface IC : IA, IB
{
}

public class All : IA, IB
{
    public void A()
    {
        Console.Out.WriteLine("ALL A");
    }

    public void B()
    {
        Console.Out.WriteLine("ALL B");
    }
}

public class Single : IC
{
    public void A()
    {
        Console.Out.WriteLine("SINGLE A");
    }

    public void B()
    {
        Console.Out.WriteLine("SINGLE B");
    }
}

class Program
{
    static void Main()
    {
        All all = new All();
        Single single = (Single)(all as IC); // Always null
        single?.A();
    }
}

Upvotes: 1

Views: 62

Answers (1)

Dai
Dai

Reputation: 155165

You will need to use the Adapter Pattern.

class AllIC : IC {
    private readonly All all;
    public AllIC(All all) {
        if( all == null ) throw new ArgumentNullException(nameof(all));
        this.all = all;
    }

    public void A() => this.all.A();
    public void B() => this.all.B();
}

static void Main()
{
    All all = new All();
    IC ic = new AllIC( all ); // Observe that `ic` is typed as interface `IC` instead of the concrete type `Single`.
    ic.A();
}

Note that unlike interfaces you cannot coerce one concrete type to another (in this case, your casting to Single), you must change your local variable type from a concrete type (Single) to an interface (IC).

Upvotes: 3

Related Questions