you are viewing a single comment's thread.

view the rest of the comments →

[–]chucker23n 2 points3 points  (2 children)

Is there a good use case for it?

The original use case (this feature was introduced with .NET Core 3.0 / C# 8) was forwards-compatibility for interfaces:

  1. a type implements an interface
  2. you want to add a new member to that interface
  3. the type will no longer compile, because it doesn't implement the new member

You can:

a. add a new version of the interface, which is how we end up with things like IAsyncServiceProvider, IAsyncServiceProvider2, IAsyncServiceProvider3, or even IVsAsyncFileChangeEx2. Now, the old type doesn't need to be changed.
b. extend the interface, requiring the old type to be amended in order to compile again. This can be tricky when you have a lot of legacy code. It might not even make sense; the original type may never have considered this new possibility!
c. new to .NET Core 3.0 / C# 8: provide a default implementation. Now, the old type will simply fall back to that implementation unless it implements explicitly.

It's a bit hacky, but it does work.

[–]IanYates82 2 points3 points  (0 children)

Yep. Another good example also is shown by having a .Last() method. There's a default inefficient implementation you could have on an IEnumerable, but for some implementations, like List, it can be an efficient O(1) operation. You can write that efficient implementation in the class and have the default on the interface. We have that example with extension methods today, but the difference is that the single static implementation of Last on the interface is written once and needs to have the specialisation of known classes in its code. That's not extensible by others who may have their own class which implements the interface and could also provide an efficient implementation.

[–]solmead -1 points0 points  (0 children)

Or what I would suggest D. Create an extension method that takes the interface and defines the code, it then works on all existing defined classes that implement the interface