C# program to demonstrate the interface

Here, we are going to demonstrate the interface in C#?
Submitted by Nidhi, on November 05, 2020

Here, we create an interface and then implement the methods of the interface into a class.

Program:

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

//C# program to demonstrate the interface

using System;

interface Inf
{
   void SayHello();
}

class ABC : Inf
{
    public ABC()
    {
        Console.WriteLine("ABC Ctor called");
    }

    public void SayHello()
    {
        Console.WriteLine("ABC: Hello World");
    }
}

class XYZ : Inf
{
    public XYZ()
    {
        Console.WriteLine("XYZ Ctor called");
    }

    public void SayHello()
    {
        Console.WriteLine("XYZ: Hello World");
    }
}

class Demo
{
    static void Main(string[] arg)
    {
        Inf[] infArray = 
        {
            new ABC(),
            new XYZ()
        };

        foreach (Inf I in infArray)
        {
            I.SayHello();
        }
    }
}

Output:

ABC Ctor called
XYZ Ctor called
ABC: Hello World
XYZ: Hello World
Press any key to continue . . .

Explanation:

In the above program, we created an interface Inf that contains a method declaration for SayHello(), and then implement the SayHello() method in both classes ABC and XYZ. Both ABC and XYZ class contains constructor.

Now look to the Demo class, the Demo class contains the Main() method. In the Main() method we created the array of interface Inf and initialized with the object of ABC and XYZ class, and then access the object using the foreach loop and called the SayHello() method for both ABC and XYZ class.

C# Basic Programs »


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




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.