C# Interface - c# - c# tutorial - c# net




What is the use of interface in C# ?

  • 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.
Interface

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.
using System;  
public interface Drawable  
{  
void draw();  
}  
public class Rectangle : Drawable  
{  
public void draw()  
{  
Console.WriteLine("drawing rectangle...");  
}  
}  
public class Circle : Drawable  
{

public void draw()  
{  
Console.WriteLine("drawing circle...");  
}  
}  
public class TestInterface  
{  
public static void Main()  
{  
Drawable d;  
d = new Rectangle();  
d.draw();  
d = new Circle();  
d.draw();  
}  
}  
click below button to copy the code. By - c# tutorial - team

C# examples - Output :

drawing rectangle...
drawing circle…

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

learn c# tutorials - Abstract vs Interface Csharp in c#

learn c# tutorial - Abstract vs Interface Csharp in c# Example

using System;  
public interface Drawable  
{  
public abstract void draw();//Compile Time Error  
}  
click below button to copy the code. By - c# tutorial - team


Related Searches to C# Interface

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add wikitechy.com to your ad blocking whitelist or disable your adblocking software.

×