C#-Interface

Interface in C#

A C#-Interface is a completely abstract class, which contains only abstract members.

It is declared using the interface keyword.

When a class implements an interface, it must also implement, or define, all of its methods.

The term implementing an interface is used (opposed to the term “inheriting from”) to describe the process of creating a class based on an interface. The interface simply describes what a class should do. The class implementing the interface must define how to accomplish the behaviors.

The syntax to implement an interface is the same as that to derive a class.


C#-Interface Example:

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();
    }
}

Recommended Posts:

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *