default method in interface c-sharp

Author : Sachin Sharma
Published On : 13 Apr 2023
Tags: c#

Before c# 8.0 interface only contain declaration of members like methods,properties,events etc but after c# 8.0 also can define and implement the method to the interface.

Now you are allowed to add implemention of method in interface without breaking the existing implementation of interface. 

Lets explain with example

interface IDisplay {
 
    // This method is only
    // have its declaration
    // not its definition
    void Display1();
 
    // Default method with both
    // declaration and definition
    public void Display2()
    {
        Console.WriteLine("Hello!! Default Method");
    }
}

public class Example: IDisplay
{   
    public void Display1()
    {
        Console.WriteLine("Hello!! Method");
    } 
}

IDisplay obj=new Example();

obj.Display1();
obj.Display2();

 

Output:

Hello!! Method
Hello!! Default Method

 

Comments

No comments have been added to this article.

Add Comment