Interface In C#

Interface

Interface used for controlling the class. Interface does not contain and implement anything but method which has created by the interface will be implemented by Class. Suppose there is a class University, Interface UGC on base and class College is a child as in the following code snippet:

  1. Interface UGC {  
  2.     Public void Get()  
  3.     Public void Display()  
  4. }  
  5. Class University: UGC  
  6. String Name, Adress, Type;  
  7. Public void Get() {  
  8.     Console.Write(“Enter the University Name, Adress and Type: ”);  
  9.     This.Name = Console.ReadLine();  
  10.     This.Adress = Console.ReadLine();  
  11.     This.Type = Console.ReadLine();  
  12. }  
  13. Public void Display() {  
  14.     Console.WriteLine(“University Name is: ”+this.Name);  
  15.     Console.WriteLine(“University Address is: ”+this.Adress);  
  16.     Console.WriteLine(“University Type is: ”+this.Type);  
  17. }  
  18. Class College: University  
  19. String Name, Adress, Type;  
  20. Public void Get() {  
  21.     Console.Write(“Enter the College Name, Adress and Type: ”);  
  22.     This.Name = Console.ReadLine();  
  23.     This.Adress = Console.ReadLine();  
  24.     This.Type = Console.ReadLine();  
  25. }  
  26. Public void Display() {  
  27.     Console.WriteLine(“College Name is: ”+this.Name);  
  28.     Console.WriteLine(“College Address is: ”+this.Adress);  
  29.     Console.WriteLine(“College Type is: ”+this.Type);  
  30. }  
  31. Class Interface_Implementation  
  32. Public void Main(); {  
  33.     College obj = new College();  
  34.     Obj.get();  
  35.     Obj.Display();  
  36. }  
  37. Console.ReadLine();  
  38. }  
  39. }  
In the above code snippet we can see UGC interface is not containing and implementing anything but the method which has created by UGC is implemented by both base and child class. Also we can tell Interface is a contract between classes about the method which was created by Interface and will be implemented by class.

Recap

Interface does not implement and contain anything but it is used for controlling the class.

 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now