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
9
votes
5 answers

C# equivalent of Java 8 Default Methods in Interface

I heard that in Java 8 there is a flexibility of having function definitions in an Interface. I think we can have some default state with this feature in all the classes that are implementing such interface. So, my question is do we have any such…
Jaganmohanreddy
  • 391
  • 4
  • 19
8
votes
3 answers

Why do I need to cast 'this' to an interface with a default implementation in C# 8.0 when I call it in the class derived form that interface?

I have this Simple Console program in .NET Core 3.1 with C# 8: using System; namespace ConsoleApp34 { public interface ITest { public void test() { Console.WriteLine("Bye World!"); } } public…
user1777224
  • 838
  • 7
  • 7
7
votes
2 answers

If default interface methods are implemented in C# 8.0 why would I ever need abstract classes?

I recently ran into a list of features that are being considered for addition in the next version of C#. One of them is called "default interface methods": https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md In…
Marko
  • 12,543
  • 10
  • 48
  • 58
6
votes
1 answer

abstract, virtual and sealed methods in interfaces of C#-8

The following interface has no errors in a .Net Core Console application with C#-8.0 interface I { public abstract void f(); public virtual void g() => Console.WriteLine("g"); public sealed void h() =>…
Minimus Heximus
  • 2,683
  • 3
  • 25
  • 50
5
votes
1 answer

Is it possible to auto-implement IEquatable and IComparable in C# 11?

When writing C#, I tend to write a lot of value type objects that implement IEquatable, IComparable, or both. For the sake of this proposal, let's assume that I'm writing a fictitious struct called Int256 with equatable and comparable value…
Matthew Layton
  • 39,871
  • 52
  • 185
  • 313
5
votes
2 answers

Why are my C# default interface implementations not being recognized in the concrete class definition?

I have a .Net 6.0 application in Visual Studio 2019. I'm trying to get default interface implementations working. For some reason, it doesn't seem to be recognizing the default implementations in the class definition. Here is a sample code…
JohnB
  • 3,921
  • 8
  • 49
  • 99
5
votes
1 answer

Using `GetMethod` on class implementing an interface with a default method implementation returns null

I have a couple interfaces (IMapFrom and IMapTo) that allow me to simplify my AutoMapper configurations. Each of the interfaces has a default implementation for the MapTo and MapFrom methods. I have a separate MappingProfile class that uses…
JD Davis
  • 3,517
  • 4
  • 28
  • 61
5
votes
3 answers

Making member virtual prevents calling default interface implementation and causes StackOverflowException in C# 8

Consider the code: class ChildClass : BaseClass { public void Method1() {} //some other method } abstract class BaseClass : IChildInterface { public virtual //<- If we add virtual so that this method can be overridden by ChildClass,…
Fit Dev
  • 3,413
  • 3
  • 30
  • 54
5
votes
1 answer

Event Inheritance with C#8 Default Interface Implementation/Traits

There is currently little documentation surrounding the limitations of events with the new C#8 default interface implementations (traits). I am particularly confused with the spec proposal. Not only is the example given invalid C# (the "override"…
jeff17237
  • 595
  • 9
  • 18
4
votes
2 answers

Default interface not found in c# class

I have this peace of code in a console app .net core 3.1 on VS 16.5.1: namespace DefaultInterfaceTest { class Program { static void Main(string[] args) { var person = new Person(); …
Fritjof Berggren
  • 3,178
  • 5
  • 35
  • 57
4
votes
2 answers

Can we replace abstract class with Interface with Default Methods in C#

In C# 8.0 we have a new feature where we can provide a default method implementation in Interfaces which can also be overridden by its implementing classes as well. We used to have Abstract classes with instance methods to provide a common…
Jaganmohanreddy
  • 391
  • 4
  • 19
3
votes
2 answers

Invoke c# event inside interface

I am trying to invoke an event in the interface in which it is defined (see code below). However, I get the following error: Program.cs(7,3): error CS0079: The event 'IMyInterface.MyEvent' can only appear on the left hand side of += or -=. I suspect…
3
votes
2 answers

C# default interface implementation - can't override

I'm following this guide https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods to use default interface implementation feature. I've copied a code that defines a default implementation in…
Random
  • 3,807
  • 2
  • 30
  • 49
3
votes
1 answer

C# 9 - How to call default interface method with reflection?

I have an interface for automapper. And DTOs implement this interfaces. As you can see there is a default method. public interface IMap { public void Mapping(Profile profile) { profile.CreateMap(typeof(T), GetType()).ReverseMap(); …
is_oz
  • 813
  • 1
  • 8
  • 27
3
votes
2 answers

Can't get C# default interface method to compile

C# 8.0 has a new feature that lets you add a default implementation to a method on an interface. Either I'm doing something wrong or this feature doesn't work as advertised. (I'm guessing it's the former.) I created a new .NET Core 3.1 console app…
Bob.at.Indigo.Health
  • 11,023
  • 13
  • 64
  • 111