Home

Using an Interface to Declare a Variable

     

Introduction

In the pure sense, you cannot use an interface or an (or a pure) abstract class to declare a variable. In a sense, when declaring a variable from a class that implements an interface or inherits from an (or a pure) abstract class, you can use the name of the interface or abstract as the starting point.

 

The rule to follow is that, after the new operator, you must use the name of the class.

Here is an example:

File: IRound.cs

public interface IRound
{
    double Radius { get; set; }
    double Diameter { get; }
    double Circumference { get; }
    double Area { get; }
}
 

File: Circle.cs

public class Circle : IRound
{
    private double rad;

    public Circle()
    {
        this.rad = 0.00D;
    }

    public Circle(double radius)
    {
        this.rad = radius;
    }

    public double Radius
    {
        get
        {
            return rad;
        }
        set
        {
            if (rad <= 0)
                rad = 0;
            else rad = value;
        }
    }

    public double Diameter
    {
        get
        {
            return rad * 2;
        }
    }

    public double Circumference
    {
        get
        {
            return rad * 2 * 3.14159;
        }
    }

    public double Area
    {
        get
        {
            return rad * rad * 3.14159;
        }
    }
}

File: Exercise.cs

using System;

public class Exercise
{
    public static int Main()
    {
        double Radius = 0;

        try
        {
            Console.Write("Enter the radius: ");
            Radius = double.Parse(Console.ReadLine());

            IRound Rnd = new Circle(Radius);

            Console.WriteLine("Radius:        {0}", Rnd.Radius);
            Console.WriteLine("Diameter:      {0}", Rnd.Diameter);
            Console.WriteLine("Circumference: {0}", Rnd.Circumference);
            Console.WriteLine("Area:          {0}", Rnd.Area);
        }
        catch (FormatException)
        {
            Console.WriteLine("Bad Value!!!");
        }
        return 0;
    }
}

Here is an example of executing the program:

Enter the radius: 35.137
Radius:        35.137
Diameter:      70.274
Circumference: 220.77209566
Area:          3878.63456260271
Press any key to continue . . .
 
 

Home Copyright © 2009-2011 C# Key