C# 8.0 Default interface methods in under 60 seconds!
Last week I noticed a new feature in C# 8.0 called Default Interface Methods. Although the official documentation is great, it's quite extensive so I thought I would do this really short and simple breakdown of what this feature enables. (Hopefully under a minute read.) 😉
Imagine that you have an interface and then you have a few classes that uses this interface. Before C# 8.0, if you want to add a method to your interface then you are forces to implement that method behaviour on every single class that uses this interface.
Before C# 8.0:
"You are forces to implement the method behaviour on every single class that uses the interface."
But what it you know that the behaviour of this method will always be the same? Feels a little unnecessary to repeat the method behaviour on every single class that uses this interface. What you'll probably do to stay DRY is you'll add a base class with the shared method implemented, but starting C# 8.0 there's a new little trick you can use. (drum roll)
Default Interface Methods:
Starting from C# 8.0 you can now define an actual method on the interface, which becomes the default method behavior and all classes that uses this interface won't have to be updated.
From C# 8.0:
"You can now add default method behavior on the interface without introducing a breaking change to all classes using this interface."
Notice that this becomes the default behaviour. You can still implement the interface method on one of your classes where you might want it to work in a slightly different way.
"You can implement default interface methods in classes where you don't want the default behaviour."
Yes, under 60 seconds! 💪
Cheers friends! ❤️