FunctionX Logo

C# Examples: Simple Inheritance

 

Introduction

This example features a simple way to perform inheritance. It creates a class called Circle that contains calculations for a circle based on its radius. It calculates the diameter, the circumference, and the area. Then, a class called Sphere inherits from the Circle class:

Source File: Circle.cs
namespace FlatShapes
{
	class Circle
	{
		private double _radius;

		public double Radius
		{
			get { return (_radius < 0) ? 0.00 : _radius; }
			set	{ _radius = value; }
		}
		public double Diameter
		{
			get	{ return Radius * 2; }
		}
		public double Circumference
		{
			get	{ return Diameter * 3.14159; }
		}
		public double Area
		{
			get	{ return Radius * Radius * 3.14159; }
		}
	}
}
Source File: Sphere.cs
namespace Volumes
{
	class Sphere : FlatShapes.Circle
	{
		new public double  Area
		{
			get	{ return 4 * Radius * Radius * 3.14159; }
		}
	
		public double Volume
		{
			get	{ return 4 * 3.14159 * Radius * Radius * Radius / 3; }
		}
	}
}
Source File: Exercise.cs
using System;
using Volumes;
using FlatShapes;

class Exercise
{
	static void Show(Circle round)
	{
		Console.WriteLine("Circle Characteristics");
		Console.WriteLine("Side:     {0}", round.Radius);
		Console.WriteLine("Diameter: {0}", round.Diameter);
		Console.WriteLine("Circumference: {0}", round.Circumference);
		Console.WriteLine("Area:     {0}", round.Area);
	}

	static void Show(Sphere ball)
	{
		Console.WriteLine("\nSphere Characteristics");
		Console.WriteLine("Side:     {0}", ball.Radius);
		Console.WriteLine("Diameter: {0}", ball.Diameter);
		Console.WriteLine("Circumference: {0}", ball.Circumference);
		Console.WriteLine("Area:     {0}", ball.Area);
		Console.WriteLine("Volume: {0}\n", ball.Volume);
	}

	public static int Main()
	{
		FlatShapes.Circle c = new FlatShapes.Circle();
		Volumes.Sphere s = new Volumes.Sphere();

		c.Radius = 20.25;
		Show(c);

		s.Radius = 20.25;
		Show(s);

		return 0;
	}
}

This would produce:

Circle Characteristics
Side:     25.55
Diameter: 51.1
Circumference: 160.535249
Area:     2050.837805975

Sphere Characteristics
Side:     25.55
Diameter: 51.1
Circumference: 160.535249
Area:     8203.3512239
Volume: 69865.2079235483
 

Home Copyright 2004 FunctionX, Inc.