Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partially implement an Interface

Tags:

c#

interface

I asked something similar but still I haven't got a clear idea. My objective is to partially implement an interface in C#.

Is it possible? Is there any pattern to achieve this result?

like image 939
GigaPr Avatar asked Feb 25 '10 19:02

GigaPr


4 Answers

An interface defines a contract. You have to fulfill that contract by implementing all of its members if you want to use it.

Maybe the use of an abstract class would work best for you, that way you can define some default behavior while allowing overrides where you need to.

like image 150
Dan Avatar answered Oct 12 '22 09:10

Dan


You can throw NotImplementedException for the methods you don't want to implement or NotSupportedException for the methods you can't implement.

It's preferable to not do this, but there are places in the .NET framework where classes throw NotSupportedExceptions and the design of Stream pretty much forces you to throw this exception for some methods.

From MSDN about NotSupportedException:

The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.

like image 31
Mark Byers Avatar answered Oct 12 '22 11:10

Mark Byers


yes you can partially implement interface if you are using abstract class something like this:

public interface myinterface
{
     void a();
     void b();
}
public abstract  class myclass : myinterface
{
    public void a()
    {
        ///do something
    }

  public   abstract void  b(); // keep this abstract and then implement it in child class
}
like image 43
2 revs, 2 users 97% Avatar answered Oct 12 '22 09:10

2 revs, 2 users 97%


As others have said an interface should be fully implemented (although there are ways around this like throwing NotSupportedExceptions)

You should take a look at The Interface Segregation Principle (one of the SOLID priciples that Robert Martin discusses) and figure out if you actually need multiple interfaces that classes can then choose which ones to implement

like image 43
Jon Erickson Avatar answered Oct 12 '22 11:10

Jon Erickson