Page d'Accueil

Interfaces

 

Introduction

Imagine you start creating a class and, while implementing or testing it, you find out that this particular class can be used instead as a general base that other classes can be derived from. An interface is a special class whose purpose is to serve as a template that actual classes can be based on. An interface is primarily created like a class: it has a name, a body and can have members.

To create an interface, instead of the class keyword, you use the interface keyword. By convention, the name of an interface starts with I. Here is an example:

interface ICourtDimensions
{
}

Practical Learning Practical Learning: Introducing Interfaces

  1. On the main menu, click Project -> Add New Item...
  2. In the Templates list, click Interface
  3. Set the Name to Quadrilateral and click Add
  4. Change the file as follows:
     
    using System;
    
    namespace Geometry1
    {
        interface IQuadrilateral
        {
        }
    }
  5. Save the file

The Members of an Interface

As done for a class, the members of an interface are listed in its body. In an interface, you cannot declare fields like those we have used in other classes. Instead, if you want some type of member variable, you can create a property. If you create a property in an interface, you cannot define that property. One of the rules of an interface is that you cannot define any of its members. This is also valid for its properties. Therefore, if you create a property in an interface:

  • You can indicate that it would be read-only by adding an empty getter property to it. Here is an example:
     
    public interface ICourtDimensions
    {
    	double Length { get; }
    }
  • You can indicate that it would be write-only by adding an empty setter property to it. Here is an example:
     
    public interface ICourtDimensions
    {
    	double Length { set; }
    }
  • You can indicate that it would be used to write values to it and to read values from it. To provide this information, add a getter and a setter accessories to it. Here is an example:
     
    public interface ICourtDimensions
    {
    	double Length { get; set; }
    }

In the same way, you can create as many properties as you judge necessary in an interface. Besides the properties, an interface can also have other types of members such as methods. Here is an example of an interface that has one read-only property named NameOfSport, one read/write property named NumberOfPlayers, and one method named SportCharacteristics:

public interface IBall
{
	int NumberOfPlayers
	{
		get;
		set;
	}

	string NameOfSport
	{
		get;
	}

	void SportCharacteristics();
}

Practical Learning Practical Learning: Creating Members of an Interface

  1. To create a property, change the file as follows:
     
    using System;
    
    namespace Geometry1
    {
        interface IQuadrilateral
        {
            double Area { get; }
        }
    }
  2. Save the file

An Interface as a Base Class

An interface is used to lay a foundation for other classes. For this reason, it is the prime candidate for class derivation. To derive from an interface, use the same technique we have applied in inheritance so far. Here is an example of a class named SportBall that derives from an interface named ISportType:

public class SportBall : ISportType
{
	int players;
	string sport;
}

Just as you can derive a class from an interface, you can create an interface that itself is based on another interface. Here is an example:

public interface ISportType : IBall
{
	SportCategory Type
	{
		get;
	}
}

The C# language doesn't allow multiple inheritance, which is the ability to create a class based on more than one class. Multiple inheritance is allowed only if the bases are interfaces. To create multiple inheritance, separate the names of interface, with a comma. Here is an example:

public interface ISportType : IBall, ICourtDimensions
{
	SportCategory Type
	{
		get;
	}
}

You can also involve a class as parent in a multiple inheritance scenario but there must be only one class. Here is an example in which a class called Sports derives from one class and various interfaces:

public interface Sports: Player, IBall, ICourtDimensions
{
}

Practical Learning Practical Learning: Inheriting From an Interface

  1. On the main menu, click Project -> Add New Item...
  2. In the Templates list, click Interface
  3. Set the Name to RightAngle and click Add
  4. Change the file as follows:
     
    using System;
    
    namespace Geometry1
    {
        interface IRightAngle : IQuadrilateral
        {
            double Base { get; set; }
            double Height { get; set; }
            double Perimeter { get; }
        }
    }
  5. Access the Square.cs file and change it as follows:
     
    using System;
    
    namespace Geometry1
    {
        public class Square : ShapeDescription, IRightAngle
        {
            . . .
        }
    }
  6. Access the Rectangle.cs file and change it as follows:
     
    using System;
    
    namespace Geometry1
    {
        public class Rectangle : ShapeDescription, IRightAngle
        {
            . . .
        }
    }
  7. Save all

Implementation of Derived Classes of an Interface

After creating an interface, you can derive other interfaces or other classes from it. If you are deriving other interfaces from an interface, you can just proceed as you see fit. For example, you can add or not add one or more new properties, you can add or not add one or more methods, etc. Here is an example:

Source File: Preparation.cs
public enum SportCategory
{
	SinglePlayer,
	Collective,
	Unknown
}

public interface ICourtDimensions
{
	double Length { get; set; }
	double Width  { get; set; }
}

public interface IBall
{
	int NumberOfPlayers
	{
		get;
		set;
	}

	string NameOfSport
	{
		get;
	}

	void SportCharacteristics();
}

public interface ISportType : IBall, ICourtDimensions
{
	SportCategory Type
	{
		get;
	}
}

If you derive a class, from an interface, you must implement all properties that were created in the interface. This means that you must define them so that, when a variable is declared of that class, the properties have meaning. In the same way, if you create a class that is based on an interface, you must implement all methods that were declared in the interface. If you derive a class from an interface that itself was derived from another interface, in your class, you must define all properties that were created in the whole parental lineage and you must implement all methods that were created in the parent and grant-parent interfaces. Here is an example:

Source File: Sport.cs
using System;

public class SportBall : ISportType
{
	int players;
	string sport;
	SportCategory _type;
	double Len;
	double Wdt;
    
	public SportBall(int nbr, SportCategory tp, string name)
	{
		players = nbr;
		_type   = tp;
		sport   = name;
	}

	public int NumberOfPlayers
	{
		get	{ return players;}
		set	{ players = value;}
	}

	public string NameOfSport
	{
		get	{ return sport; }
	}

	public SportCategory Type
	{
		get	{ return _type; }
	}

	public double Length
	{
		get { return Len; }
		set { Len = value; }
	}

	public double Width
	{
		get { return Wdt; }
		set { Wdt = value; }
	}

	public void SportCharacteristics()
	{
		Console.WriteLine("Sport Characteristics");
		Console.WriteLine("Name of Sport: {0}", NameOfSport);
		Console.WriteLine("Type of Sport: {0}", Type);
		Console.WriteLine("# of Players:  {0}", NumberOfPlayers);
		Console.WriteLine("Court Dimensions: {0}m x {1}m", Len, Wdt);
	}
}

Once the class is ready, you can then use it as you see fit. Here is an example:

Source File: Exercise.cs
using System;

class Exercise
{
    static void Main()
    {
	SportBall volley = new SportBall(6,
					 SportCategory.Collective,
					 "Volley Ball");
	volley.Length = 18;
	volley.Width  = 9;
	volley.SportCharacteristics();

	Console.WriteLine();

	SportBall tennis = new SportBall(1,
					 SportCategory.SinglePlayer,
					 "Table Tennis");
	tennis.Length = 23.7;
	tennis.Width  = 8.25;
	tennis.SportCharacteristics();

	Console.WriteLine();
    }
}

This would produce:

Sport Characteristics
Name of Sport: Volley Ball
Type of Sport: Collective
# of Players:  6
Court Dimensions: 18m x 9m

Sport Characteristics
Name of Sport: Table Tennis
Type of Sport: SinglePlayer
# of Players:  1
Court Dimensions: 23.7m x 8.25m

Practical Learning Practical Learning: Implementing Derived Members of an Interface

  1. Access the Square.cs file and change it as follows:
     
    using System;
    
    namespace Geometry1
    {
        public class Square : ShapeDescription, IRightAngle
        {
            private double _side;
    
            public Square()
            {
                _side = 0.00;
            }
    
            public Square(double s)
            {
                _side = s;
            }
    
            public override string Name
            {
                get { return "Square"; }
            }
    
            public override string Description()
            {
                // Get the introduction from the parent
                string Introduction = base.Description() + " " +
                    "A square is a quadrilateral that has four " +
                      "equal sides and four right angles";
    
                return Introduction;
            }
    
            public double Base
            {
                get { return (_side < 0) ? 0.00 : _side; }
                set { _side = value; }
            }
    
            public double Height
            {
                get { return (_side < 0) ? 0.00 : _side; }
                set { _side = value; }
            }
    
            public double Area
            {
                get { return Base * Base; }
            }
    
            public double Perimeter
            {
                get { return Base * 4; }
            }
        }
    }
  2. Access the Rectangle.cs file and change it as follows:
     
    using System;
    
    namespace Geometry1
    {
        public class Rectangle : ShapeDescription, IRightAngle
        {
            double _length;
            double _height;
    
            public Rectangle()
            {
                _length = 0.00;
                _height = 0.00;
            }
    
            public Rectangle(double L, double H)
            {
                _length = L;
                _height = H;
            }
    
            public override string Name
            {
                get { return "Rectangle"; }
            }
    
            public override string Description()
            {
                // Get the introduction from the parent
                string Introduction = base.Description();
    
                string Msg = Introduction + " " +
                      "\nA rectangle is a quadrilateral that has adjacent " +
                "perpendicular sides. This implies that its four " +
                             "angles are right.";
                return Msg;
            }
    
            public double Base
            {
                get { return _length; }
                set { _length = value; }
            }
    
            public double Height
            {
                get { return _height; }
                set { _height = value; }
            }
    
            public double Area
            {
                get{ return Base * Height; }
            }
    
            public double Perimeter
            {
                get { return 2 * (Base + Height); }
            }
        }
    }
  3. Access the Program.cs file and change it as follows:
     
    using System;
    
    namespace Geometry1
    {
        public class Program
        {
            static Square CreateASquare()
            {
                double side;
    
                Console.Write("Enter the side of the square: ");
                side = double.Parse(Console.ReadLine());
    
                Square Sqr = new Square(side);
                return Sqr;
            }
    
            static void DisplaySquare(Square S)
            {
                Console.WriteLine("Square Characteristics");
                Console.WriteLine("Name:        {0}", S.Name);
                Console.WriteLine("Description: {0}", S.Description());
                Console.WriteLine("----------------------------");
                Console.WriteLine("Side:        {0}", S.Base);
                Console.WriteLine("Perimeter:   {0}", S.Perimeter);
                Console.WriteLine("Area:        {0}", S.Area);
            }
    
    
            static Rectangle CreateARectangle()
            {
                double Len, Hgt;
    
                Console.WriteLine("Enter the dimensions of the rectangle");
                Console.Write("Base:   ");
                Len = double.Parse(Console.ReadLine());
                Console.Write("Height: ");
                Hgt = double.Parse(Console.ReadLine());
    
                Rectangle Recto = new Rectangle(Len, Hgt);
                return Recto;
            }
    
            static void DisplayRectangle(Rectangle R)
            {
                Console.WriteLine("Rectangle Characteristics");
                Console.WriteLine("Name:        {0}", R.Name);
                Console.WriteLine("Description: {0}", R.Description());
                Console.WriteLine("----------------------------");
                Console.WriteLine("Base:        {0}", R.Base);
                Console.WriteLine("Height:      {0}", R.Height);
                Console.WriteLine("Perimeter:   {0}", R.Perimeter);
                Console.WriteLine("Area:        {0}", R.Area);
            }
    
            static void Main()
            {
                Square Sq = new Square();
                Rectangle Rect = new Rectangle();
    
                Sq = CreateASquare();
                Rect = CreateARectangle();
    
                Console.WriteLine("============================");
                DisplaySquare(Sq);
                Console.WriteLine("============================");
                DisplayRectangle(Rect);
                Console.WriteLine("============================");
    
                Console.WriteLine();
            }
        }
    }
  4. Execute the application and test it. Here is an example:
     
    Enter the side of the square: 44.16
    Enter the dimensions of the rectangle
    Base:   58.62
    Height: 36.06
    ============================
    Square Characteristics
    Name:        Square
    Description: A quadrilateral is a geometric figure that has 
    four sides and four angles. A square is a quadrilateral that 
    has four equal sides and four right angles
    ----------------------------
    Side:        44.16
    Perimeter:   176.64
    Area:        1950.1056
    ============================
    Rectangle Characteristics
    Name:        Rectangle
    Description: A quadrilateral is a geometric figure that has 
    four sides and four angles.
    A rectangle is a quadrilateral that has adjacent perpendicular 
    sides. This implies that its four angles are right.
    ----------------------------
    Base:        58.62
    Height:      36.06
    Perimeter:   189.36
    Area:        2113.8372
    ============================
    
    Press any key to continue . . .
  5. Close the DOS window
 

Home Copyright 2006-2007 Yevol