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)
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.
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.
In This Oracle tutorial I got "You cannot declare member interfaces in a local class." because "interfaces are inherently static."
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.
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(); }
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With