Reputation: 1828
I have an interface which is common to Class A, B and C. But now I need to add two methods which is only applicable for Class B and not applicable for classes A & C. So, do I need to add these two methods to the common interface itself and throw not implemented exception in class A & C or is there any better way to do this?
interface ICommon
{
Method1;
Method2;
Method3;
Method4;
}
Class A: ICommon
{
Method1;
Method2;
}
Class B: ICommon
{
Method1;
Method2;
Method3;
Method4;
}
Class C: ICommon
{
Method1;
Method2;
}
Thanks in advance
Upvotes: 2
Views: 181
Reputation: 12944
If your interface has the methods, you simply MUST implement them, but you can do it secretly:
Class A: ICommon
{
public void Method1()
{
}
public void Method2()
{
}
void ICommon.Method3()
{
throw new NotSupportedException();
}
void ICommon.Method4()
{
throw new NotSupportedException();
}
}
This is exactly how an array implemments the IList
interface and hides members like Add
.
Upvotes: 1
Reputation: 151588
If two classes have to implement the same interface but one of the classes needs more methods than the interface contains, those methods do not belong in that interface. Otherwise the other class would also need those methods.
Interfaces describe behaviour, like IDisposable dictates a Dispose() method. If your Method3() and Method4() implement certain behaviour, you should extract an interface from those two methods only and apply that interface to classes that need those methods.
Upvotes: 0
Reputation: 17269
If these methods are common to other classes (not just B):
Have B extend another interface
interface ICommon2
{
Method3;
Method4;
}
class B : ICommon, ICommon2
{
Method1;
Method2;
Method3;
Method4;
}
If these methods are specific to only B:
class B : ICommon
{
Method1;
Method2;
Method3;
Method4;
}
Upvotes: 8