My favorite design improvement for C# 8 has to be the ability to add the default implementation of a method or property to an existing interface.
Just think about it, if you have defined a public interface and a bunch of down stream components consume it, any changes you make to the interface immediately need to be reflected by the class consumers, no exceptions. This feature allows you to postpone downstream change because the interface itself holds a concrete method or property it can fall back on.
Take this example interface:
interface IFileHandler { void Delete(string filename); }
Implemented here:
class MyFile : IFileHandler { public void Delete(string filename) { System.IO.File.Delete(filename) } }
I can now make changes to the interface without immediately modifying the previous class:
interface IFileHandler { void Delete(string filename); void Rename(string filename, string newfilename) => System.IO.File.Move(filename, newfilename); }
This new design permits consumers of your interface the opportunity to implement their own version of the method of property at will, no need for wholesale code changes. You can head over to Microsoft docs and go over the details by following a tutorial.
Admittedly, the idea kind of rubbed me the wrong way when I first saw it, as the whole point of an interface is the framework of the contract, not the implementation details, this was quickly offset by the convenience it could give API consumers. I was also, incorrectly, assuming this might invalidate the need for base classes, but you can't inherit from interfaces. So if you want inheritable public members you still need to put them in an abstract base class.
Just a note about the default implementation in this code sample. It makes an assumption that the physical file system is used, and this could break implementers and unit tests. I wrote an article with some more details if you are interested: https://jeremybytes.blogspot.com/2019/09/c-8-interfaces-dangerous-assumptions-in.html
I'd be glad to have a conversation about it if you're interested.
Take care,
Jeremy
Comments are closed.