C# program to implement an interface in a structure

Here, we are going to learn how to implement an interface in a structure in C#?
Submitted by Nidhi, on October 14, 2020

Here, we will implement an interface in a structure.

Program:

The source code to implement an interface in a structure is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to implement an interface in a structure.

using System;

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

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

struct Sample : MyInf1,MyInf2
{
    //Method definitions
    void MyInf1.Method()
    {
        Console.WriteLine("MyInf1.Method() called");
    }
    void MyInf2.Method()
    {
        Console.WriteLine("MyInf2.Method() called");
    }
}


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

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

        M1.Method();
        M2.Method();
    }
}

Output:

MyInf1.Method() called
MyInf2.Method() called
Press any key to continue . . .

Explanation:

Here, we created the two interfaces MyInf1 and MyInf2. Both Interfaces contains the declaration of Method(). After that, we implemented both interfaces into structure Sample with method definitions.

void MyInf1.Method()
{
    Console.WriteLine("MyInf1.Method() called");
}
void MyInf2.Method()
{
    Console.WriteLine("MyInf2.Method() called");
}

Here, we have to specify the interface name with method name to define the method inside the structure Sample.

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 the Sample structure. But we called Method() using both references that will print the corresponding message on the console screen.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.