Questions tagged [default-interface-member]

A default interface member is a feature introduced in C# 8 which allows an interface to declare a member with a body. Classes which implement the interface are not required to override a default method. Use this tag for questions relating to C# 8's default interface members

Default interface members were introduced in . They are similar to Java's feature.

An interface member can now be specified with a code body, and if an implementing class or struct does not provide an implementation of that member, no error occurs. Instead, the default implementation is used.

Default interface members help in the following scenarios :

  • Interface versioning
  • Interoperation with APIs targeting Android (Java) and iOS (Swift), which support similar features.
  • To implement without requiring multiple inheritance, similar to PHP and Scala traits. Java 8 and later also supports traits through default interface methods
  • Code Reuse in structs (Thanks Eirik Tsarpalis!)

Interface Versioning

This example is adapted from Mads Torgersen's article on Default implementations in interfaces:

Let’s say that we offer the following interface:

interface ILogger
{
    void Log(LogLevel level, string message);
}

And a class that implements it :

class ConsoleLogger : ILogger
{
    public void Log(LogLevel level, string message) { ... }
}

With default members, the interface can be modified without breaking ConsoleLogger :

interface ILogger
{
    void Log(LogLevel level, string message);
    void Log(Exception ex) => Log(LogLevel.Error, ex.ToString());
}

The ConsoleLogger still satisfies the contract provided by the interface: if it is converted to the interface and the new Log method is called it will work just fine - the interface’s default implementation is just called:

public static void LogException(ConsoleLogger logger, Exception ex)
{
    ILogger ilogger = logger; // Converting to interface
    ilogger.Log(ex);          // Calling new Log overload
}

An implementing class that does know about the new member is free to implement it in its own way. In that case, the default implementation is just ignored.

Traits

In an imaginary game, items may inherit from a GameItem class :

public class GameItem    {    }

Let's assume that a potion doesn't have a location, nor does it move :

public class Potion:GameItem{}

A rock may have a location :

public interface ILocatable
{
    public (double x,double y) Location{get;set;}
}

public class Rock:GameItem,ILocatable
{
    public (double x,double y) Location{get;set;}
}

A player or monster can also move. Without traits, one possible solution would be to add the ability to move to GameItem or introduce an intermediate abstract class with that functionality. Modifying GameItem would also affect Rock while the abstract class would introduce a relation that probably isn't appropriate.

This can be solved with the IMovable trait, which can be applied to any type that has a Location property :

public interface IMovable
{
    public abstract (double x,double y) Location{get;set;}
    void Move(double angle,double speed)
    {              
          var x=Location.x + speed*Math.Sin(angle);
          var y=Location.y + speed*Math.Cos(angle);
          Location=(x,y);
    }
}    

That trait can be applied to any class as long as it has a matching Location property:

public class Player:GameItem,ILocatable,IMovable
{
    public (double x,double y) Location{get;set;}
}

public class Monster:GameItem,ILocatable,IMovable
{
    public (double x,double y) Location{get;set;}
}

Trait Example - Reading settings in a container environment

In container-based or serverless applications, one of the most common ways to distribute settings is through environment variables. DIMs can be used to create a trait that retrieves a specific environment variable each time it's called, eg :

interface IGithubSettings
{
    public string CurrentToken  => Environment.GetEnvironmentVariable("GitHubToken");
}

References :

61 questions
63
votes
8 answers

How would you implement a "trait" design-pattern in C#?

I know the feature doesn't exist in C#, but PHP recently added a feature called Traits which I thought was a bit silly at first until I started thinking about it. Say I have a base class called Client. Client has a single property called Name. Now…
mpen
  • 272,448
  • 266
  • 850
  • 1,236
34
votes
2 answers

Do C# 8 default interface implementations allow for multiple inheritance

According to https://blogs.msdn.microsoft.com/dotnet/2018/11/12/building-c-8-0/, one of the new features coming in C# 8 is the default implementation of interfaces. Will this new feature also implicitly allow for multiple inheritance? If not, what…
Roy Stoof
  • 343
  • 3
  • 6
32
votes
8 answers

Calling C# interface default method from implementing class

C# 8 supports default method implementations in interfaces. My idea was to inject a logging method into classes like this: public interface ILoggable { void Log(string message) => DoSomethingWith(message); } public class MyClass : ILoggable { …
Andi
  • 3,234
  • 4
  • 32
  • 37
29
votes
6 answers

Default Interface Methods. What is deep meaningful difference now, between abstract class and interface?

I know that an abstract class is a special kind of class that cannot be instantiated. An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but, it cannot be instantiated. The…
20
votes
1 answer

Unexpected behavior of a C# 8.0 default interface member

Consider the following code: interface I { string M1() => "I.M1"; string M2() => "I.M2"; } abstract class A : I {} class C : A { public string M1() => "C.M1"; public virtual string M2() => "C.M2"; } class Program { static void…
18
votes
3 answers

How could the function defined in the interface with the body be redefined in the inherited function without overriding?

Can somebody explain how same function on same class behaved different? using System; public class HelloWorld { public static void Main(string[] args) { MyUpperScript mAsdfScript = new MyUpperScript(); IInterface…
17
votes
2 answers

Default implementation in interface is not seen by the compiler?

Here is a my code inside a c# project that targets .NET Core 3.0 (so I should be in C# 8.0) with Visual Studio 2019 (16.3.9) public interface IJsonAble { public string ToJson() => System.Text.Json.JsonSerializer.Serialize(this); } public class…
Christophe Blin
  • 1,687
  • 1
  • 22
  • 40
15
votes
1 answer

What is the difference between an interface with default implementation and abstract class?

C# 8.0 has introduced a new language feature – default implementations of interface members. public interface IRobot { void Talk(string message) { Debug.WriteLine(message); } } The new default interface implementations provides…
Postlagerkarte
  • 6,600
  • 5
  • 33
  • 52
14
votes
2 answers

When should we use default interface method in C#?

In C# 8 and later, we have default interface methods, so: Doesn't it ruin the principle of interface? When should we use default interface methods instead of base (abstract) class?
Hassan Monjezi
  • 1,060
  • 1
  • 8
  • 24
11
votes
3 answers

Can a C# class call an interface's default interface method from its own implementation?

If I have a default interface method like this: public interface IGreeter { void SayHello(string name) => System.Console.WriteLine($"Hello {name}!"); } Can I have my concrete implementation call that default method? public class HappyGreeter :…
D. Patrick
  • 2,894
  • 26
  • 37
10
votes
2 answers

Contravariance invalid when using interface's delegate as a parameter type

Consider the contravariant interface definition with a delegate: public interface IInterface { delegate int Foo(int x); void Bar(TInput input); void Baz(TInput input, Foo foo); } The definition of Baz fails with an…
V0ldek
  • 9,623
  • 1
  • 26
  • 57
10
votes
1 answer

How can I call the default method instead of the concrete implementation

Why is the behavior of Default Interface Methods changed in C# 8? In the past the following code (When the Default interface methods was demo not released): interface IDefaultInterfaceMethod { // By default, this method will be virtual, and the…
Bassam Alugili
  • 16,345
  • 7
  • 52
  • 70
10
votes
2 answers

Default interface methods and default values for Auto Properties

Given that an auto property compiles to a get_method, a set_method and a private variable and since C# 8 is introducing default interface methods Can properties in Interfaces have default implementations? Especially a get only property?
John Demetriou
  • 4,093
  • 6
  • 52
  • 88
10
votes
2 answers

Default Interface Methods in C# 8

Consider the following code example: public interface IPlayer { int Attack(int amount); } public interface IPowerPlayer: IPlayer { int IPlayer.Attack(int amount) { return amount + 50; } } public interface ILimitedPlayer: IPlayer { …
Bassam Alugili
  • 16,345
  • 7
  • 52
  • 70
9
votes
1 answer

C#8 interface defaults: How to implement default properties in a nice and usable way

I really loved the idea of default implementations on interfaces in C#8. But after trying it the disappointment was big... So here's a simple example which I've found a part of the answer to in C#8 interfaces with properties/methods defined in them…
Soko
  • 774
  • 1
  • 7
  • 20
1
2 3 4 5