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:
1 2 3 4 |
partial interface IPersistable { void Load(int i); } |
Our manual changes go into a different file, again using the partial keyword:
1 2 3 4 |
partial interface IPersistable { void Save(object o); } |
Our code can use those methods without knowing that those methods come from different files:
1 2 3 4 |
IPersistable persistable = new MemoryStore(); persistable.Save("demo"); persistable.Load(42); |
To implement this interface, we can again separate the generated code from our manually written one:
1 2 3 4 5 6 7 |
public partial class MemoryStore : IPersistable { public void Load(int i) { Console.WriteLine($"Load was called for {i}"); } } |
1 2 3 4 5 6 7 |
public partial class MemoryStore : IPersistable { public void Save(object o) { Console.WriteLine($"Save was called for {o}"); } } |
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.