C# program to implement the same method in multiple classes

Here, we are going to learn how to implement the same method in multiple classes in C#?
Submitted by Nidhi, on October 14, 2020

Here, we will implement a method with the same prototype in multiple classes.

Program:

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

//C# program to implement the same method in multiple classes.

using System;

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

class Sample1 : MyInterface
{
    //Method definition
    public void Method()
    {
        Console.WriteLine("Sample1:Method() called");
    }    
}

class Sample2 : MyInterface
{
    //Method definition
    public void Method()
    {
        Console.WriteLine("Sample2:Method() called");
    }    
}

class Sample3 : MyInterface
{
    //Method definition
    public void Method()
    {
        Console.WriteLine("Sample3:Method() called");
    }    
}

class Program
{
    public static void Main(String[] args)
    {
        MyInterface M;
        
        M = new Sample1();
        M.Method();

        M = new Sample2();
        M.Method();

        M = new Sample3();
        M.Method();
    }
}

Output:

Sample1:Method() called
Sample2:Method() called
Sample3:Method() called
Press any key to continue . . .

Explanation:

Here, we created an interface MyInterface that contains the declaration of the method Method(). Then we created three classes Sample1, Sample2, and Sample3, and we implemented the Method() in all three classes.

Now look to the Program class, it contains the Main() method, the Main() method is the entry point for the program. Here, we created the reference M of MyInterface and then initialized M by objects of all classes one by one and call implemented methods that will print corresponding messages 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.