Interface in C#
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();
}
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();
}
}
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;
}
}
}
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();
}
}
}
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
Note- A class has to implement all the methods defined in the interface. Other wise program will throw an error.
Output
Interface in C#
Reviewed by LanguageExpert
on
July 15, 2018
Rating:
No comments