Roslyn: Proposal: Partial interface implementation a.k.a. Traits

Created on 29 Dec 2016  路  6Comments  路  Source: dotnet/roslyn

I believe C# could benefit from from a feature similar to traits in Scala, or mixins in other languages. This proposal could be a potential implementation for asks in both #73 or #258. The main difference would be in the implementation.

Benefits

  • Reduce boilerplate by enabling the definition of default or universal implementations on interfaces.
  • Maintain the DRY rule for code that may make heavy use of common interfaces.

Syntax

interface IFoo {

     void DoStuff();

     void DoThing() => { Console.WriteLine("Did Things"); }
}

Syntax: Overriding default implementation

Goal: Don't introduce new complexity, just reuse "override" here

class Bar : IFoo {

     void DoStuff(){
          //Do stuff here
     }

     override void DoThing(){
          //My new impl goes here
     }
}

This example, while contrived demonstrates a scenario where I've chosen to implement one of the two functions in the interface, For the implementation, I've chosen explicitly to use expression bodied methods as the implementor of the functionality.

Side Note: I wonder how much IEquatable code is being copied and pasted between classes in code bases because this feature is missing.

Area-Language Design Resolution-Duplicate

Most helpful comment

@wmccullough There are multiple requests about it and I guess that there are more out there. . :)

16074

8127

60

All 6 comments

@wmccullough There are multiple requests about it and I guess that there are more out there. . :)

16074

8127

60

Thank you, believe it or not I did search this beforehand and had little luck, perhaps because the terms are all used a hundred times in different situations.

This is actually more related to #258.

This appears to be a dup of #258.

Let's not forget how this relates to #4586 :) Scala has the with keyword which composes traits.
I saw a talk where Martin Odersky said they are replacing with a more precise & (with isn't recursive but & will be)

We are now taking language feature discussion on https://github.com/dotnet/csharplang for C# specific issues, https://github.com/dotnet/vblang for VB-specific features, and https://github.com/dotnet/csharplang for features that affect both languages.

Traits are now proposed at https://github.com/dotnet/csharplang/issues/52 and are under active design/development.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

orthoxerox picture orthoxerox  路  3Comments

glennblock picture glennblock  路  3Comments

AdamSpeight2008 picture AdamSpeight2008  路  3Comments

joshua-mng picture joshua-mng  路  3Comments

MadsTorgersen picture MadsTorgersen  路  3Comments