In c# 8.0, default interface methods are features, that allow developers to add methods to an interface without breaking existing implementations.
This feature lets you add new methods with default implementations to an interface, ensuring backward compatibility for older classes that implement the interface.
Developers can provide a method body when defining a method in an interface, similar to an abstract class. This allows a default implementation that can be used by implementation classes.
Default interface methods make it easy to configure interfaces without breaking existing implementations. They also allow code sharing between types, enabling multiple properties and attributes.
Android and iOS have useful default interface options to facilitate interaction with similar products. They also allow developers to use the Traits programming technique which enforces methods to be reused between unrelated classes.
In this example, we demonstrate the use of an interface with a method having a default implementation:
csharpusing System; namespace SampleCoding { public interface IExampleInterface { void RegularMethod(); // Default method with a body void DefaultMethod() { Console.WriteLine("Default implementation of DefaultMethod in the interface."); } } public class ExampleClass : IExampleInterface { public void RegularMethod() { Console.WriteLine("Implementation of RegularMethod in the class."); } } public class Program { static void Main() { ExampleClass example = new(); // Call regular method example.RegularMethod(); // To call the default method, cast to the interface IExampleInterface interfaceRef = example; interfaceRef.DefaultMethod(); } } }
Output
Note: In C#, we cannot directly call a default interface method from an instance of the implementing class unless the class explicitly implements the method. We need to access the default interface method via an interface reference, not a class reference.
In this example, if we have an ISensor interface, we can add a new Reset() method with a default implementation. Any class that implements ISensor will automatically inherit the default behavior unless it chooses to override it:
csharpusing System; public interface ISensor { string GetStatus(); // Default method with a body void Reset() { Console.WriteLine("Default reset implementation."); } } public class TemperatureSensor : ISensor { public string GetStatus() { return "Temperature Sensor: Active"; } // No need to implement Reset, as it has a default implementation in the interface } public class Program { public static void Main() { ISensor sensor = new TemperatureSensor(); // Call the GetStatus method Console.WriteLine(sensor.GetStatus()); // Call the default Reset method sensor.Reset(); } }
Output
Copyrights © 2024 letsupdateskills All rights reserved