Below are the two different examples from the book Illustrated C# 2012. In the first example Hypotenuse is declared as readonly
. In second example PI
and numberofsides
are declared as readonly
. Why is PI
assigned a value and numberofsides
is not?
Can const
be used to declare PI
and assign a value to it? Let's say if I want to implement right triangle portion of class shape in second example. How do it do it with numberofsides
are already declared and the sides have no values assigned. I mean how do I find out which side is hypotenuse?
class RightTriangle
{
public double A = 3;
public double B = 4;
public double Hypotenuse // Read-only property
{
get{ return Math.Sqrt((A*A)+(B*B)); } // Calculate return value
}
}
class Program
{
static void Main()
{
RightTriangle c = new RightTriangle();
Console.WriteLine("Hypotenuse: {0}", c.Hypotenuse);
}
}
class Shape
{
// Keyword Initialized
// ↓↓
readonly double PI = 3.1416;
readonly int NumberOfSides;
// ↑↑
// Keyword Not initialized
public Shape(double side1, double side2) // Constructor
{
// Shape is a rectangle
NumberOfSides = 4;
// ↑
// ... Set in constructor
}
public Shape(double side1, double side2, double side3) // Constructor
{
// Shape is a triangle
NumberOfSides = 3;
// ↑
// ... Set in constructor
}
}