Home »
.Net »
C# Programs
C# - Interface Example
Here, we are going to demonstrate the example of an interface in C#?
Submitted by Nidhi, on November 05, 2020 [Last updated : March 22, 2023]
Here, we create an interface and then implement the methods of the interface into a class.
C# program to demonstrate example the interface
The source code to demonstrate the interface is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# - Interface Example
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 »