user972255
user972255

Reputation: 1828

C# - Interface/Class design issue

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

Answers (3)

Martin Mulder
Martin Mulder

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

CodeCaster
CodeCaster

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

Steven Wexler
Steven Wexler

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

Related Questions