The last few years have seen a huge proliferation of interfaces for C# classes. These interfaces are very useful for DI, testing and mocking. But they come at a cost: while extracting an interface is fairly easy, you now have to keep interface and class in sync. Especially in an evolving project, this can quickly become annoying. Change a parameter on the class? Edit the interface, too! Change to class-doc? Edit the interface, too. This is tedious, and smaller things like parameter names and documentation get out of sync quickly.
Luckily, C# Source Generators offer the ability to automatically generate these interfaces for us. I even wrote a post about this topic last year, but the birth of our second child prevented me from finishing my idea. Finally, I was able to complete the code and publish it as a NuGet Package: AutomaticInterface .
AutomaticInterface takes care of creating an interface for a class – it automatically copies all public properties, methods, events and the documentation to the interface. You can use it like a normal interface and every change to your class will be picked up by the interface in the next build.
How to use it
- Install the nuget:
dotnet add package AutomaticInterface - Create an attribute with the name
[GenerateAutomaticInterface]. You can just copy the minimal code from the repo . It’s the easiest way to get that attribute because you cannot reference any code from the analyzer package. - Let your class implement the interface, e.g.
SomeClass: ISomeClass - Build the solution, the interface should now be available.
This will create this interface:
More articles in this subject area
Discover exciting further topics and let the codecentric world inspire you.
Blog author
Christian Sauer
Do you still have questions? Just send me a message.
Do you still have questions? Just send me a message.