CSharp - Interface Interface Definition

Introduction

An interface acts as a specification or contract between types.

Interface members are all implicitly abstract.

A class (or struct) can implement multiple interfaces.

A class can inherit only one class.

An interface declaration provides no implementation for its members.

These members will be implemented by the classes and structs that implement the interface.

An interface can contain only methods, properties, events, and indexers.

Interface members are always implicitly public and cannot declare an access modifier.

Syntax

Here is an example of interface.

interface Printable{
    bool Print();
}

Implementing an interface means providing a public implementation for all its members:

class Countdown : Printable
{
       int count = 11;
       public bool Print() => Console.WriteLine(count--);
}

You can implicitly cast an object to any interface that it implements. For example:

Printable e = new Countdown();
Console.Write (e.Print());     

Demo

using System;
interface Printable
{
    void Print();
}
class Countdown : Printable
{
    int count = 11;
    public void Print() => Console.WriteLine(count--);
}
class MainClass//from   www.  ja v  a  2 s  .c o  m
{
    public static void Main(string[] args)
    {
        Printable e = new Countdown();
        e.Print();
    }
}

Result

Related Topics

Quiz