Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing interfaces in partial classes

Consider a class which implements a lot of interfaces, would it make sense to implement each interface in a separate file using partial class definitions?

Would this be an abuse of the language feature or is it an idiom I'm unaware of?

like image 988
Motti Avatar asked Jan 13 '11 14:01

Motti


People also ask

Can a partial class implement an interface?

Partial Keyword in C# can be applied to Class, Interfaces, and Struct. By using the Partial keyword in a class, we can divide the class definitions and other properties into different files.

How do you implement an interface partially?

A class can provide partial implementations of the implemented interfaces. If a class does not provide the full implementation of interfaces, it must be declared abstract. ABCImpl has to be abstract since it does not implement all methods from IABC. We can further implement the methods from interface in subclass.

Can we implement interface partially in C#?

In C#, you can split the implementation of an interface into multiple files using the partial keyword. The partial keyword indicates that other parts of the interface can be defined anywhere in the namespace. All the parts must use the partial keyword and must be available at compile time to form the final type.

Can different parts of a partial class inherit from different interfaces?

Any method, interface, and function declared on a partial class is available for all the other parts. The source file name for each part of the partial class can be different, but each partial class's name must be the same.


2 Answers

If your class has to implement many interfaces, that's a reasonable way of managing the source, yes. You can edit the project file to make several of them depend on one "main" class file, which makes the Solution Explorer easier to work with.

You should ask yourself whether you shouldn't have several smaller classes each implementing a single interface though. Sometimes that will be a better approach, sometimes not - but it's always worth asking the question.

like image 182
Jon Skeet Avatar answered Oct 22 '22 00:10

Jon Skeet


Not an idiom I have ever heard of, but sounds like an elegant way to partition your code.

like image 29
Oded Avatar answered Oct 22 '22 01:10

Oded