Using an Interface to Declare a Variable
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…
1 min read57 words4 code samples
Introduction#
In the strict sense, an interface cannot be instantiated directly, but a class can implement it and provide the required members. In this example, the interface serves as the contract that the class follows. Here is an example:
C#
public interface IRound
{
double Radius { get; set; }
double Diameter { get; }
double Circumference { get; }
double Area { get; }
}File: Circle.cs
C#
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
C#
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:
C#
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

