Simple Interface Example in C#

In this example, we will learn how to implement simple interface using C# program?
Submitted by Nidhi, on October 14, 2020 [Last updated : March 21, 2023]

Here, we will demonstrate the working of the interface using a simple example.

C# program to implement simple interface

The source code to demonstrate the simple interface is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Simple Interface Example in C#

using System;

interface MyInterface
{
    //Method Declaration
    void Method1();
    void Method2();
    void Method3();
}

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

    public static void Main(String[] args)
    {
        MyInterface M = new Sample();

        M.Method1();
        M.Method2();
        M.Method3();
    }
}

Output

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

Explanation

Here, we created an interface MyInterface that contains the declaration of three methods Method1(), Method2(), and Method3().

Here, we also created a class Sample that implements the interface MyInterface. Here, we defined the methods Method1(), Method2(), and Method3(). The Sample class also contains the Main() method. The Main() method is the entry point for the program. Here, we created the reference of the MyInterface interface and initialized with the object of Sample class and called all three methods, that will print corresponding messages on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





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