How to implement an interface in C#

Syntax

The general form of a class that implements an interface is shown here:


class class-name : interface-name {
  // class-body
}

To implement more than one interface, the interfaces are separated with a comma. A class can inherit a base class and also implement one or more interfaces.

The name of the base class must come first in the comma-separated list. The methods that implement an interface must be declared public.

Example

The following code defines an interface.


using System;//from   w w w.  j a va 2  s.com

interface Printable{
    void Print();
   
}

class Rectangle : Printable{
    int Width;
    
    public void Print(){
       Console.WriteLine("Width:"+Width);
    }
}
class Test
{
    static void Main()
    {
        Printable r = new Rectangle();

        r.Print();
    }
}

The output:

Example 2

Multiple Implementation: implement two interfaces


interface IFoo/*ww w.j  a v  a  2s .co m*/
{
    void ExecuteFoo();
}

interface IBar
{
    void ExecuteBar();
}

class Tester: IFoo, IBar
{
    public void ExecuteFoo() {}
    public void ExecuteBar() {}
}

Example 3

extend class and implement interface at the same time


public class Component
{//from   w  w w.j  a v a 2  s  .co  m
    public Component() {}
}

interface Printable
{
    void printHeader(float factor);
    void printFooter(float factor);
}

public class TextField: Component, Printable
{
    public TextField(string text)
    {
        this.text = text;
    }
    // implementing Printable.printHeader()
    public void printHeader(float factor)
    {        
    }    
    // implementing Printable.printFooter()
    public void printFooter(float factor)
    {        
    }    
    private string text;
}

class MainClass
{
    public static void Main()
    {
        TextField text = new TextField("Hello");
        
        Printable scalable = (Printable) text;
        scalable.printHeader(0.5F);
        scalable.printFooter(0.5F);
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor