Q:

C# program to demonstrate the interface

0

C# program to demonstrate the interface

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | Class, Object, Methods

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to check a specified type is a value ty... >>
<< C# program to print the current assembly name usin...