Pages

Showing posts with label Constants. Show all posts
Showing posts with label Constants. Show all posts

Sunday, 14 June 2015

Constants & ReadOnly

Member Constants

Member constants are like the local constants, except that they’re declared in the class declaration rather than in a method. Same as local constants haracteristics, member constant :
  • Initialized value must be computable at compile time and is usually one of the predefined simple types or an expression composed of them.
  • Can not be assigned after its declaration.
Member constants, however, are more interesting than local constants, in that they act like static values. They’re “visible” to every instance of the class, and they’re available even if there are no instances of the class. Unlike statics, constants do not have their own storage locations and are substituted in by the compiler at compile time in a manner similar to #define values in C and C++.
class circle
{
 private const float PI = 3.416F; //Constants member
 public int radius;                  
 public string color;                
 
 public float getArea()
 {
  return PI * radius * radius;
 }

 public void showCircle()
 {
  Console.WriteLine("radius: " + radius + " color: " + color + " area:" + getArea());
 }
}

class Program
{
 static void Main()
 {
  circle circle1 = new circle() { radius = 20, color = "yellow" } ;
  circle circle2 = new circle() { radius = 5, color = "blue" };

  Console.WriteLine("showing circle1");
  circle1.showCircle();
  Console.WriteLine("showing circle2");
  circle2.showCircle();
  Console.Read();
 }
}

readonly Modifier

A field can be declared with the readonly modifier. The effect is similar to declaring a field as const, in that once the value is set, it cannot be changed. Some different characteristics are:
  • While a const field can only be initialized in the field’s declaration statement, a readonly field can have its value set in any of the following places:
    • The field declaration statement—like a const.
    • Any of the class constructors. If it’s a static field, then it must be done in the static constructor.
  • While the value of a const field must be determinable at compile time, the value of a readonly field can be determined at run time. This additional freedom allows you to set different values under different circumstances or in different constructors.
  • Unlike a const,readonly field can be either an instance field or a static field and has a storage location in memory.
Let's change PI constant to readonly fields, eventhough it's not a proper encapsulation. Just to show you how to create a readonly field.
class circle
{
 private readonly float PI;          //readonly field declaration
 public int radius;                 
 public string color;       

 public circle()
 {
  PI = 3.416F;                    //assign value to PI
 }
 ....
}

static void Main()
{
 circle circle1 = new circle() { radius = 20, color = "yellow" } ;
 circle circle2 = new circle() { radius = 5, color = "blue" };

 Console.WriteLine("showing circle1");
 circle1.showCircle();
 ....
}

Variables and Constants

Variables

Local Variables Like fields, it stores data. While fields usually store data about the state of the object, local variables are usually created to store data for local, or transitory, computations.
Instance Field Local Variable
Lifetime Starts when the class instance is created. Ends when the class instance is no longer accessible Starts at the point in the block where it is declared. Ends when the block completes execution.
Implicit initialization Initialized to a default value for the type No implicit initialization. The compiler produces an error message if nothing is assigned to the variable before it’s used.
Storage area Because instance fields are members of a class, all instance fields are stored in the heap, regardless of whether they’re value types or reference types. Value type: Stored on the stack. Reference type: Reference stored on the stack and data stored in the heap.

The following line of code shows the syntax of local variable declarations.
static void Main(string[] args)
{
 int counter = 5;
 person me = new person("Yang","Sopiana",29);
 ....
}

Local Variables Inside Nested Blocks

Method bodies can have other blocks nested inside them.
  • There can be any number of blocks, and they can be sequential or nested further. Blocks can be nested to any level.
  • Local variables can be declared inside nested blocks, and like all local variables, their lifetime and visibility are limited to the block in which they’re declared and the blocks nested within it.
See following example
static void Main(string[] args)
{
 int counter1;    //counter1's lifetime is until Main method finish
 ....  //some statements
 {
  int counter2 = 20;  //counter2's lifetime is until closing curly brace
  .... //some other statements
 }
}

Constants

A local constant is much like a local variable, except that once it is initialized, its value can’t be changed. Like a local variable, a local constant must be declared inside a block. The two most important characteristics of a constant are the following:
  • A constant must be initialized at its declaration.
  • A constant cannot be changed after its declaration.
The core declaration for a constant is shown following. The syntax is the same as that of a field or variable declaration, except for the following:
  • The addition of the keyword const before the type.
  • The mandatory initializer. The initializer value must be determinable at compile time and is usually one of the predefined simple types or an expression made up of them. It can also be the null reference, but it cannot be a reference to an object, because references to objects are determined at run time.
Use following syntax to create constant
const [Type] [Identifier] = [value];

Example:
double calculateCircleArea(double radius)
{
 const double PI = 3.1416;   // Declare local constant
 return  radius * radius * PI; // Read from local constant

}