Pages

Sunday, 14 June 2015

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

}

0 comments:

Post a Comment