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#
using System;
interface interface1
{
void MyMethod1();
}
interface interface2
{
void MyMethod2();
}
struct GFG : interface1, interface2
{
void interface1.MyMethod1()
{
Console.WriteLine( "interface1.Method() is called" );
}
void interface2.MyMethod2()
{
Console.WriteLine( "interface2.Method() is called" );
}
}
class Geeks{
public static void Main(String[] args)
{
interface1 M1;
interface2 M2;
M1 = new GFG();
M2 = new GFG();
M1.MyMethod1();
M2.MyMethod2();
}
}
|
Output:
interface1.Method() is called
interface2.Method() is called