Multiple Interfaces in the Same Class Example in C#

In this example, we will learn how to implement multiple interfaces in the same class using C# program?
Submitted by Nidhi, on October 14, 2020 [Last updated : March 21, 2023]

Here, we will implement two interfaces in the same class. Each interface contains a method declaration.

C# program to implement multiple interfaces in the same class

The source code to implement multiple interfaces in the same class is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to implement multiple interfaces 
//in the same class.

using System;

interface MyInf1
{
    //Method Declaration
    void Method1();
}

interface MyInf2
{
    //Method Declaration
    void Method2();
}

class Sample : MyInf1,MyInf2
{
    //Method definitions
    public void Method1()
    {
        Console.WriteLine("Method1() called");
    }
    public void Method2()
    {
        Console.WriteLine("Method2() called");
    }    
}

class Program
{
    public static void Main(String[] args)
    {
        MyInf1 M1;
        MyInf2 M2;

        M1 = new Sample();
        M2 = new Sample();

        M1.Method1();
        M2.Method2();
    }
}

Output

Method1() called
Method2() called
Press any key to continue . . .

Explanation

Here, we created the two interfaces MyInf1 and MyInf2. Interface MyInf1 contains the declaration of Method1() and interface MyInf2 contains the declaration of Method2(). After that, we implemented both interfaces into class Sample with method definitions.

Now look to the Program class, It contains the Main() method, the Main() method is the entry point for the program. Here we created two references M1 and M2.

M1 = new Sample();
M2 = new Sample();

Here, both references initialized with the object of Sample class. But we can call Method1() using M1 and Method2() can be called by M2 only.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.