Interface in c#

 Introduction:

In c#, Interface can be defines by a Keyword call Interface, We use Interface in c# for abstraction purposes and in situations, where we want to hide the actual logic of out program.

In interfaces there is a simple rule which states that any class which inherits an interface must implement all the methods which were initialized inside that particular interface. 

We can only initialize the functions or the methods inside the Interface but we cannot code inside them as those are to be implemented by another class, which will implement this particular interface.

In this example, we will create an Interface in a c# console based application and we will implement methods inside that Interface by creating another class. 

Lets take a look at how it looks with an example.

Step 1: Create a new C# console based application in Visual Studio 2017 by clicking at New, Project and and from the left sidebar choose GetStarted and then choose Console App  and we will name it as InterfaceBasics and then click OK to create this new Project.



Step 2: In program.cs, we will first up create an Interface and we will name it as IBasicInterface and we will just initialize two methods inside this interface for understand purpose.

The first method will return the string and the second method will take that particular string coming from the first method, we have named our methods as f1() and f2() respectively.


Step 3: In the next step we will create a class named as InterfaceTest and implement that particular Interface, this is how it should be implemented in visual studio, enter crtl+. and choose the option implement Interface.


Step 4:  After implementing the interface, its time to define the methods inside the InterfaceTest class, so this is how it looks like after defining the two methods.


Step 5:  In this next step we will call the methods of the InterfaceTest class from the main function inside the program.cs.

 So, here we initialized an object obj for the InterfaceTest class  and we then we called the two methods f1 and f2 from the Main function, so the first method will return a string, so we get that in a variable called someString and then we passed that string to the 2nd function which is f2, and this is how the entire code looks like.


Press crtl+f5 and the run the program to see the output window.


Talha Mahmood

I have been developing Applications in Microsoft .NET technologies since 2015, and having more then 5 years of experience in .NET Technology and SQL database, also having hands in tools like C# Windows Forms, WPF, WCF, Asp.Net Web forms, Asp.Net Core, SSRS, LINQ, Entity Framework, Crystal Reports, SQL server, MySQL, MongoDB, Document DB, JQuery, JavaScript, Oracle, Web API.

Post a Comment

Previous Post Next Post