3

C# 8 adds the option for default method implementation in interfaces, meaning a method CAN be defined in the interface.

In a situation when I DON'T need a default constructor, nor inherited fields in the derived classes, what should I default to: An interface with a default implementation, or the old-school way of an abstract class?

Is there a convention for styling for this case?

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • C# 8 isn't even final yet; it's a little early to start asking for *conventions*. Default interface implementations were not added with the intent of obsoleting abstract classes, that's the closest thing to a factual statement on the matter. – Jeroen Mostert Jul 19 '19 at 14:06
  • 2
    The interface default implementations have mainly two reasons to be: 1. You want to add new members to an existing interface without breaking existing code. 2. You want to program with traits. (see: http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf) – Olivier Jacot-Descombes Jul 19 '19 at 14:11
  • Afaik the default implementations are explicitly implemented, so they don't show up as accessible members of the derived class. It won't be a difficult choice. – H H Jul 19 '19 at 14:14
  • 2
    Let's wait until [2080](https://github.com/dotnet/csharplang/milestone/8). – Sinatr Jul 19 '19 at 14:25
  • @HenkHolterman: It would be cool if we could specify that we want an implicit implementation: https://github.com/dotnet/csharplang/issues/1062#issuecomment-513252820 – Olivier Jacot-Descombes Jul 19 '19 at 14:47
  • It's not a matter of *styling*, there are substantial differences. An `abstract` class adds an inheritance relation. A child class `is-a` base class. Default interface members though implement *traits* - there's no inheritance relation. The trait gives some reusable code to the classes that use it. Those classes can easily *ignore* that code by implementing the default members themselves. A trait can also *require* members from the implementing classes through the `abstract` keyword – Panagiotis Kanavos Sep 09 '19 at 15:34
  • So the answer really boils down to inheritance - do you need it or not? Which makes this question too broad to answer as we don't know anything about your domain – Panagiotis Kanavos Sep 09 '19 at 15:35

0 Answers0