Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Interface/Class design issue

Tags:

c#

oop

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

like image 887
user972255 Avatar asked Jan 27 '26 13:01

user972255


2 Answers

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;
}
like image 131
Steven Wexler Avatar answered Jan 29 '26 01:01

Steven Wexler


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.

like image 43
Martin Mulder Avatar answered Jan 29 '26 02:01

Martin Mulder