HI WELCOME TO Sirees

C# Interface

Leave a Comment
Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are declared inside the interface are abstract methods. It cannot have method body and cannot be instantiated.

It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve fully abstraction because it cannot have method body.

Its implementation must be provided by class or struct. The class or struct which implements the interface, must provide the implementation of all the methods declared inside the interface.

C# interface example

Let's see the example of interface in C# which has draw() method. Its implementation is provided by two classes: Rectangle and Circle.
  1. using System;  
  2. public interface Drawable  
  3. {  
  4.     void draw();  
  5. }  
  6. public class Rectangle : Drawable  
  7. {  
  8.     public void draw()  
  9.     {  
  10.         Console.WriteLine("drawing rectangle...");  
  11.     }  
  12. }  
  13. public class Circle : Drawable  
  14. {  
  15.     public void draw()  
  16.     {  
  17.         Console.WriteLine("drawing circle...");  
  18.     }  
  19. }  
  20. public class TestInterface  
  21. {  
  22.     public static void Main()  
  23.     {  
  24.         Drawable d;  
  25.         d = new Rectangle();  
  26.         d.draw();  
  27.         d = new Circle();  
  28.         d.draw();  
  29.     }  
  30. }  
Output:
drawing ractangle...
drawing circle...

Note: Interface methods are public and abstract by default. You cannot explicitly use public and abstract keywords for an interface method.


  1. using System;  
  2. public interface Drawable  
  3. {  
  4.     public abstract void draw();//Compile Time Error  
  5. }  

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.