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
1
vote
1 answer

.NET 6 WebAPI Controller with Default Interface Implementation methods for IActionResult doesn't create methods

I was attempting to use Interfaces with default implementation methods to add common methods to WebAPI controllers by simply implementing the interface. Implementing the interface compiles and builds, but ultimately the API methods are not created…
1
vote
3 answers

How can we use default implementation of different interfaces?

As I know, I need to upcast an instance of an inherited class to the interface where a needed method is implemented and then call it. interface IProcess { void Do() { Console.WriteLine("doing"); } //... } interface IWait { void Wait() {…
Roman
  • 21
  • 1
  • 5
1
vote
2 answers

How do I provide a default implementation in a child interface?

If I have an interface IExampleInterface: interface IExampleInterface { int GetValue(); } Is there a way to provide a default implementation for GetValue() in a child interface? I.e.: interface IExampleInterfaceChild : IExampleInterface { …
Xenoprimate
  • 7,691
  • 15
  • 58
  • 95
1
vote
2 answers

C#8.0: Protected properties for interfaces with default implementations

Say I have the following interfaces: public interface IReturnableAs { protected String ReturnAs { get; set; } } public interface IReturnableAsImage { protected String ImageResolution { get; set; } public T ReturnAsImage(String…
b12629
  • 75
  • 1
  • 5
1
vote
1 answer

Does default implementation of Interface members in C# 8 relates to overcome multiple inheritance problem of abstract class?

I'm reading this blog of .NET Engineering Team and they have introduced a new feature of default implementation for Interface. I'm confused related to its motive other than multiple level inheritance problem of abstract class. Other than that I'm…
Sahil Sharma
  • 1,813
  • 1
  • 16
  • 37
0
votes
1 answer

Why is my implemented Method from the Interface lost in the class?

I have a builder structure where I have a base interface that has everything implemented for every builder and then concrete interfaces for the specific methods. Now I face the problem, that a certain method from the most basic interface is just…
0
votes
2 answers

Making sure a C# method matches the signature of an interface default implementation

Consider the following C# example: using System; interface IExample { public int Foo() => 42; } class ExampleImplementation : IExample { public int Foo() => 37; } class Program { static void Main(string[] args) { IExample…
ph3rin
  • 4,426
  • 1
  • 18
  • 42
0
votes
0 answers

C# 9 default implementations causing errors

I have been having issues with default implementations in c# 9. Here is my problem. Each time I try to use the default implementation, I get this error 'ToyotaCorolla' does not contain a definition for 'canOffroad' and no accessible extension method…
0
votes
0 answers

Is there no way to call the default interface method in an implementing class?

Consider this interface and class implementer interface I { string M() => "I.M()"; } class C: I { public string M()=>???.Replace("I","C"); } Instead of ??? what is the way to invoke the default method? I've tried base.M(), but it wasn't a…
Michael B
  • 7,512
  • 3
  • 31
  • 57
0
votes
2 answers

Bug in C# 8.0 compiler or .NET Core 3 run-time?

I think I may have found an issue with either the C# 8.0 compiler or the .NET Core run-time regarding default interface member implementations and generic type parameter constraints. The general gist of it is that I implemented a very simple design…
0
votes
0 answers

Can not access interface default implementation method from within derived class

I am trying the new features of C#8 and i have come to this problem. Having an interface with a default implementation method , i am defining a derived class that calls the said method inside it (constructor or proprietary method). Why am i not able…
Bercovici Adrian
  • 8,794
  • 17
  • 73
  • 152
0
votes
0 answers

What happened to the ability to override default interface implementations in C# 8, .Net Core 3?

The C# 8 proposal for default interface methods shows the following example... using static System.Console; interface IA { void M() { WriteLine("IA.M"); } } interface IB : IA { override void IA.M() // The modifier…
Verax
  • 2,409
  • 5
  • 27
  • 42
0
votes
2 answers

Async all the way when using pipeline

If I have an application that uses a pipeline with many stages to be executed using foreach on all the stages and call: CanExecute Execute Interface is this: public interface IService { bool CanExecute(IContext subject); IContext…
0
votes
1 answer

How to retain some of the interface methods' default implementations in the implementing class in C# 8.0?

One would think that in C# 8.0 you should be able to do the following (according to this (1st snippet)): public interface IRestApiClient : IRestClient { ... Task PostPrivateAsync(string action, OrderedDictionary
rvnlord
  • 3,487
  • 3
  • 23
  • 32
0
votes
2 answers

abstract interface methods in C# 8 preview

I try: public interface I { abstract void F(); } I get: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. However I can find no mention of this feature ie in…
kofifus
  • 17,260
  • 17
  • 99
  • 173