Interface C# Example- C# Interface contains properties, methods, and events etc. as we have in classes. But interfaces only contains declarations and no implementation.
A class which inherit an interface is responsible to implement all the methods or items presents in the framework or user interface.
To create an interface in C#, we use “interface” keyword. For example
//interface c# code example
interface A {
void f1();
void f2();
void f3();
}
Note that we precede interface name with letter I only for readability purpose as a good naming convention.
e.g. IA, IB and IC etc. as just by looking at the name, we can understand that this is an interface and it has nothing to do with compiler error.
Interface methods are public by default and we don’t need to write public modifier. If we write public, compiler will flash an error i.e. modifier public is not valid.
There are two types of interface in C# that is C# Implicit and Explicit interface.
If we derive a class from an Interface, the class will be forced to implement all methods of the Interface. If we don’t implement interface method compiler will flash
an error.
For example, below TV class is derived from Screen interface, so, class must implement all interface method.
interface Screen {
void LED();
void LCD();
}
// TV class will override and implement both methods
class TV : Screen {
//interface implementation
public void LED() {
Console.WriteLine("TV has LED Screen");
}
public void LCD() {
Console.WriteLine("TV has LCD Screen");
}
}
A class can implement multiple interfaces as explained in this technical interview question that is a scenario where only interface can be used and not abstract class in C#
C# program example using an Interface
interface Screen {
void LED();
void LCD();
}
// TV class will override and implement both methods
class TV : Screen {
//interface implementation
public void LED() {
Console.WriteLine("TV has LED Screen");
}
public void LCD() {
Console.WriteLine("TV has LCD Screen");
}
}
/*
* Test - Interface methods example
*/
public class Sample {
public static void Main(String[] args) {
TV t = new TV();
t.LED();
t.LCD();
}
}
Output:
TV has LED Screen
TV has LCD Screen