breezmacinc.com all in one guide for every developer.

Menu

Interfaces In C# Programming – A Complete Guide

Interfaces in C# programming is a very crucial concept and quite confusing for a lot of developers to understand and implement. So I have created C# interfaces article to make sure, even a basic developer also can understand.

After going through this article, you will get the complete knowledge of interfaces like

What is an interface?

When to use interfaces?

Where to use interface?

C# Interfaces | Interfaces In C#

Let’s understand what c# interfaces are?.

Interfaces are declared using interface keyword. An interface is like a contract that all derived classes/interfaces should follow.

In other words, it’s like rules defined in the interface and these interface rules has to be followed by derived class or interfaces. So remember we are defining rules in interfaces and forcing them to follow in next subclasses.

Example: How to declare and implement interfaces in c#?

How to define Interface in C# | C# Interfaces Example

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

//How to declare interface

publicinterfaceIInput{

// interface members or defining rules

voidGetkeyBoard();

voidGetMouse();

}

//Implement interfaces in derived class

publicclassComputer:IInput

{

//implement methods or rules implementation

voidgetkeyBoard(){

system.console.write("keybaord Inetialised");

}

voidgetMouse(){

system.console.write("Mouse Inetialised");

}

}

//Implement interfaces in derived class

publicclassLaptop:IInput

{

//implement methods or rules implementation

voidgetkeyBoard(){

system.console.write("keybaord Inetialised");

}

voidgetMouse(){

system.console.write("Mouse Inetialised");

}

}

If you look at the above code, we have declared “IInput” interface with two methods (rules).

getkeyBoard()

getMouse()

In subsequent classes of Computer and Laptop, I am implementing the same rules defined in IInput Interface. I hope now you understood how to create rules and implement methods (rules) using interfaces in c#.

Features about Interfaces in c#

Interfaces are declared using interface keyword.

All methods in interfaces are by default public and we can’t change them.