Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you attach an interface to a defined class

Tags:

c#

interface

Here is the situation. In some cases I find myself wanting a class, let's call it class C that has the same functionalities as class A, but with the addition that it has interface B implemented. For now I do it like this:

class C : A,B
{
   //code that implements interface B, and nothing else
}

The problem will come if class A happens to be sealed. Is there a way I can make class A implement interface B without having to define class C (with extension methods or something)

like image 328
Mario Stoilov Avatar asked Mar 25 '14 12:03

Mario Stoilov


People also ask

Can an interface be defined in a class?

Yes, you can define an interface inside a class and it is known as a nested interface. You can't access a nested interface directly; you need to access (implement) the nested interface using the inner class or by using the name of the class holding this nested interface.

How do you add an interface to a class?

To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.

Why is it not allowed to declare an interface within a class?

In This Oracle tutorial I got "You cannot declare member interfaces in a local class." because "interfaces are inherently static."

Can an interface subclass a class?

If you do not specify that the interface is public, then your interface is accessible only to classes defined in the same package as the interface. An interface can extend other interfaces, just as a class subclass or extend another class.


2 Answers

Basically: no. That is part of what "mixins" could bring to the table, but the C# languauge doesn't currently support that (it has been discussed a few times, IIRC).

You will have to use your current approach, or (more commonly) just a pass-through decorator that encapsulates A rather than inheriting A.

class C : IB
{
    private readonly A a;
    public C(A a) {
        if(a == null) throw new ArgumentNullException("a");
        this.a = a;
    }

    // methods of IB:
    public int Foo() { return a.SomeMethod(); }
    void IB.Bar() { a.SomeOtherMethod(); }
}
like image 143
Marc Gravell Avatar answered Oct 22 '22 11:10

Marc Gravell


The only way I see, is to change inheritance to aggregation, like this:

class C : B
{
    public C(A instanceToWrap)
    {
        this.innerA = instanceToWrap;
    }

    //coda that implements B

    private A innerA;
}

There seems to be a possibility to inject interface in run-time, as it is done with Array class and IEnumerable<T> interface, but it seems a bit of an overkill.

like image 24
BartoszKP Avatar answered Oct 22 '22 10:10

BartoszKP