tags:

views:

142

answers:

3

Hi 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?

or

any pattern to achieve this result?

thanks

+12  A: 

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.

Dan
@Dan: "You have to fulfill that contract by implementing all of its members if you want to use it." Not always. Jason came up with a good counterexample: IEnumerator.
Mark Byers
+9  A: 

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.

Mark Byers
In fact, the guidelines for `IEnumerator.Reset` are to throw `NotSupportedException` if the enumerator does not support resetting to the initial position.
Jason
@Jason, Yes, some Streams also do it (see my update). But personally I think the abstract Stream class is an ugly design. But it's the way it is, so you're pretty much forced to throw NotSupportedException in some cases. It might have been better to make several different Stream interfaces. I wonder if the team that made the Stream class would make the same design choices if they had to design it again from scratch.
Mark Byers
+2  A: 

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

Jon Erickson