C# interface implementation

In this chapter you will learn:

  1. How to implement an interface
  2. Code to show how to create and implement interface
  3. Multiple Implementation: implement two interfaces
  4. extend class and implement interface at the same time

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;/*  w ww .  j a  v  a 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//  w  w w  .  ja v a 2s.c o  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.  ja  va  2  s .c  o 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.

Next chapter...

What you will learn in the next chapter:

  1. When do we need explicit interface implementation
Home »
  C# Tutorial »
    C# Types »
      C# Interface
C# Interfaces
C# interface implementation
C# Explicit interface
C# Interface inheritance
C# Indexer in an interface
C# Interface Properties
C# struct and interface
C# virtual interface