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?
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.
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 NotSupportedException
s 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.
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
}
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
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