Open In App

C# Program to Implement an Interface in a Structure

Last Updated : 15 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Structure is a value type and a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types. We can create a structure by using struct keyword. A structure can also hold constructors, constants, fields, methods, properties, indexers, and events, etc. 

Syntax:

public struct 
{
    // Fields
    // Methods
}

Interface is like a class, it can also have methods, properties, events, and indexers as its members. But interfaces can only have the declaration of the members. The implementation of the interface’s members will be given by the class that implements the interface implicitly or explicitly. Or we can say that it is the blueprint of the class.

Syntax:

interface interface_name
{
    // Method Declaration in interface
}

Now given that two interfaces, now our task is to implement both interfaces in a structure.

Approach:

  • Create two interfaces named interface1 and interface2 with method declaration in it.
  • Create a structure that implements these interfaces.
struct GFG : interface1, interface2
{
    // Method definition for interface method
    // Method definition for interface method
}
  • Write the method definitions for both interfaces in the GFG struct.
  • Inside the main method, create the two objects named M1 and M2.
  • Call the methods of interface1 and interface2 using M1 and M2 object and display the output.

Example:

C#




// C# program to illustrate how to implement
// interface in a structure
using System;
 
// Interface 1
interface interface1
{
     
    // Declaration of Method
    void MyMethod1();
}
 
// Interface 2
interface interface2
{
     
    // Declaration of Method
    void MyMethod2();
}
 
// Structure which implement interface1
// and interface2
struct GFG : interface1, interface2
{
     
    // Method definitions of interface 1
    void interface1.MyMethod1()
    {
        Console.WriteLine("interface1.Method() is called");
    }
     
    // Method definitions of interface 2
    void interface2.MyMethod2()
    {
        Console.WriteLine("interface2.Method() is called");
    }
}
 
class Geeks{
 
// Driver code   
public static void Main(String[] args)
{
     
    // Declare interfaces
    interface1 M1;
    interface2 M2;
     
    // Create objects
    M1 = new GFG();
    M2 = new GFG();
     
    M1.MyMethod1();
    M2.MyMethod2();
}
}


Output:

interface1.Method() is called
interface2.Method() is called


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads