Saturday, October 20, 2018

C# Interface Tutorial with Example

What is an Interface Class?

Interfaces are used along with classes to define what is known as a contract. A contract is an agreement on what the class will provide to an application.
An interface declares the properties and methods. It is up to the class to define exactly what the method will do.
Let's look at an example of an interface by changing the classes in our Console application. Note that we will not be running the code because there is nothing that can be run using an interface.
Let's create an interface class. The class will be called "ViastudyInterface." Our main class will then extend the defined interface. All the code needs to be written in the Program.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
interface ViastudyInterface
namespace DemoApplication { {
String GetTutorial();
void SetTutorial(int pID, string pName); }
protected int TutorialID;
class ViastudyTutorial : ViastudyInterface { protected string TutorialName;
TutorialName = pName;
public void SetTutorial(int pID, string pName) { TutorialID = pID; } public String GetTutorial() {
pTutor.SetTutorial(1,".Net by Viastudy");
return TutorialName; } static void Main(string[] args) { ViastudyTutorial pTutor = new ViastudyTutorial();
Console.WriteLine(pTutor.GetTutorial()); Console.ReadKey(); }
Code Explanation:-
  1. We first define an interface called "ViastudyInterface." Note that the keyword "interface" is used to define an interface.
  2. Next, we are defining the methods that will be used by our interface. In this case, we are defining the same methods which are used in all of earlier examples. Note that an interface just declares the methods. It does not define the code in them.
  3. We then make our ViastudyTutorial class extend the interface. Here is where we write the code that defines the various methods declared in the interface. This sort of coding achieves the following
  • It ensures that the class, ViastudyTutorial, only adds the code which is necessary for the methods of "SetTutorial" and "GetTutorial" and nothing else.
  • It also ensures that the interface behaves like a contract. The class has to abide by the contract. So if the contract says that it should have two methods called "SetTutorial" and "GetTutorial," then that is how it should be.
  • An interface defines a contract which the class will comply with. The interface defines what are the operations that the class can perform.

No comments:

Post a Comment