An interface looks almost like a class. The interface will have only declarations for methods,
properties, events, and indexers and no implementations, unlike class.
Interfaces have to be inherited by classes and structs and when inherited the respective classes
must provide implementations for all the interface members declared in the interface.
Few things to remember:
- The members in the interface are public by default.
- A class can inherit multiple interfaces at a time. This is only possible with interfaces as a class cannot inherit multiple classes.
Example 1: Simple Example for Interface by Inheritance
using System;
namespace SampleProgram {
interface ISample {
void MethodKK();
}
class Program: ISample {
public void MethodKK() {
Console.WriteLine(“Interface method here ! ”);
}
public static void Main(string[] args) {
Program pg = new Program();
pg.MethodKK();
}
}
}
The output will be:
Interface method here!
Example 2: Simple Example for Interfaces to showcase multiple Inheritance.
using System;
namespace SampleProgram {
interface ISample1 {
void MethodKK1();
}
interface ISample2 {
void MethodKK2();
}
class Program: ISample1,
ISample2 {
public void MethodKK1() {
Console.WriteLine(“Interface method 1 here ! ”);
}
public void MethodKK2() {
Console.WriteLine(“Interface method 2 here ! ”);
}
public static void Main(string[] args) {
Program pg = new Program();
pg.MethodKK1();
pg.MethodKK2();
}
}
}
The output will be:
Interface method 1 here!
Interface method 2 here!
Example 3: Interfaces having same method. Use typecast while invoking respective methods.
class Program: ISample1,
ISample2 {
public void MethodKK1() {
Console.WriteLine(“Interface method 1 here ! ”);
}
public void MethodKK2() {
Console.WriteLine(“Interface method 2 here ! ”);
}
public static void Main(string[] args) {
Program pg = new Program();
pg.MethodKK1();
pg.MethodKK2();
}
}
}
public void MethodKK() {
Console.WriteLine(“Interface method here ! ”);
}
public static void Main(string[] args) {
Program pg = new Program();
pg.MethodKK();
}
}
}
The output will be:
Interface method 1 here!
Interface method 2 here!