Partial Interfaces in C# – They Exist and There Is a Use Case for Them

Partial classes are a great way to keep (automatically) generated code away from manually written one. All you need to do is to use the partial keyword in front of your class definition and the compiler will combine those partial classes to one single class.

At work, we currently try to figure out a way that would offer us the same flexibility but for interfaces. We have generated classes and can generate an interface for their methods, but we want to be able to extend the functionality with partial classes for the more complex cases. How can we get those methods in the (manually written) partial class in the same interface, without risking those changes to be overwritten with the next run of the generator?

As it turns out, we can use the partial keyword with interfaces. That allows us to use the concept of partial classes 1:1 with interfaces. We can generate our interface with the partial keyword like this one:

Our manual changes go into a different file, again using the partial keyword:

Our code can use those methods without knowing that those methods come from different files:

To implement this interface, we can again separate the generated code from our manually written one:

This overlooked feature of C# allows us to reuse a concept we already know and put it to use in a new way. We can focus on implementing our code generator without adding more mental load to the developers using our code. I hope this approach can help you with your challenges as well.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.