Interface in C#


interface is an another aspect of object oriented programming. An interface contains the declaration of properties,methods ,events. To implement these methods , a class must implement interface and define the methods in the interface. An interface is useful in a scenarios where there are multiple class that needs to have the same methods/functions. In this case , an interface can be defined containing only the method declaration and rest is the responsibility of the class to implement the interface and the methods according to class functionality.

A class can implement multiple interfaces. If a class implements an interface, It must implement all the methods declared in interface.

An Interface declaration is similar to class declaration. To declare an interface , interface keyword is used.

Syntax

public interface IAnimal {
void run();
void hunt();
}


Implementing Interface

Class c1:interface_name
{
}


Example

using System;
namespace InterfaceDemo
{
public interface Operations
{
void buyItems(string s1,string s2);
int showAmount();
}
}


Class Implementing interface.

using System;
namespace InterfaceDemo
{
public class ItemsList : Operations
{
private string item1;
private string item2;
private int amt;
public ItemsList(int a)
{
amt = a;
}
public void buyItems(string sI1,string sI2)
{
item1 = sI1;
item2 = sI2;
Console.WriteLine("Items to buy \" {0}\" , \"{1}\"", item1, item2);
}
public int showAmount()
{
return amt;
}
}
}


Main Class

using System;
namespace InterfaceDemo
{
class Program
{
static void Main(string[] args)
{
ItemsList i = new ItemsList(2000);
i.buyItems("Cooler", "Sofa");
int k=i.showAmount();
Console.WriteLine("Amount to be given is {0}", k);
Console.ReadKey();
}
}
}


Explanation

  • First we created an class file and declared an interface in it named operation
  • We declared two methods in this one with two parameters and other with return type.
  • Then we created as class called as ItemsList and implemented the interface operation.
  • We implemented both the methods defined in the interface in the class ItemsList
  • Finally in the main class , we created an object of ItemsList class and called the two methods.


  • Note- A class has to implement all the methods defined in the interface. Other wise program will throw an error.

    Output

    Interface in C# Interface in C# Reviewed by LanguageExpert on July 15, 2018 Rating: 5

    No comments