Pages

Showing posts with label variables. Show all posts
Showing posts with label variables. Show all posts

Monday, 15 June 2015

Variable

Variable

Variable is a name that represents data stored in memory during program execution, in the other words, it represents storage location that has a modifiable value.
C# provides four kind of variable like below:
Name Description
Local variable Holds temporary data within the scope of a method. Not a member of a type.
Field Holds data associated with a type or an instance of a type. Member of a type.
Parameter A temporary variable used to pass data from one method to another method.
Array element One member of a sequenced collection of (usually) homogeneous data items. Can be either local or a member of a type.

Let's take a look to the example:
using System;

namespace Program2
{
 class person
 {
  public string firstName;
  public string lastName;
  public ushort age;

  public void greet()
  {
   Console.WriteLine("Hello "+ firstName + " " + lastName);
  }

  public void talk(string words)
  {
   Console.WriteLine(firstName+" "+ lastName + " say "+ words);
  }
 }

 class Program
 {
  static void Main(string[] args)
  {
   person me=null;

   string personFirstName = "Yang";
   string personLastName = "Sopiana";
   ushort personAge = 29;
   string personSaidWord;

   me = new person();
   me.firstName = personFirstName;
   me.lastName = personLastName;
   me.age = personAge;
   me.greet();

   Console.Write("What Do you want to say:");
   personSaidWord = Console.ReadLine();

   me.talk(personSaidWord);
  }
 }
}
The above code will result:
Hello Yang Sopiana
What Do you want to say: Lets learn C#
Yang Sopiana say Lets learn C#

line :5-20 it's userdefined type definition to make our own-defined type named person
line :7-9 it's declaration of field firstName,lastName and age
[Type Name] [Variable Name]
line :11 & 16 it's method declaration
line :16 (string words) is declaration of parameter named words
line :18 This is the way to use variable value and show it into screen
line :26 Instantiation of userdifined type person to variable named me
line :28-30 Declaration local variable with initial value
[Type Name] [Variable Name] = [Value]
line :23-36 Asignment of me object's field
line :33 & 42 Method greet & talkinvocation.

Automatic Initialization

In previous code, we see some variables has initializer and some aren't.
Some kinds of variables are automatically set to default values if they are declared without an initializer, and others are not. Variables that are not automatically initialized to default values contain undefined values until the program assigns them a value.
Variable Stored In Auto-initialized Use
Local variables Stack or stack and heap No Used for local computation inside a function member
Class fields Heap Yes Members of a class
Struct fields Stack or heap Yes Members of a struct
Parameters Stack No Used for passing values into and out of a method
Array elements Heap Yes Members of an array

null and void

null indicates that a variable is set to nothing. Only reference types can be assigned the value null.

It is important to note that assigning the value null to a reference type is distinct from not assigning it at all. In other words, a variable that has been assigned null has still been set, and a variable with no assignment has not been set and therefore will likely cause a compile error if used prior to assignment.

Sometimes the C# syntax requires a data type to be specified but no data is passed. For example, if no return from a method is needed, C# allows the use of void to be specified as the data type instead. The use of void as the return type indicates that the method is not returning any data and tells the compiler not to expect a value. void is not a data type per se, but rather an identification of the fact that there is no data type.

Nullable Modifier

As I pointed out earlier, value types cannot be assigned null because, by definition, they can’t contain references, including references to nothing. However, this cause a problem in the real world, where values are missing or maybe unknown.
To declare variables that can store null you use the nullable modifier, ?.
int count = null;               //compile error because int can't be assigned to null
int? counter2 = null;   //can be compiled

Assigning null to value types is especially attractive in database programming. Frequently, value type columns in database tables allow nulls. Retrieving such columns and assigning them to corresponding fields within C# code is problematic, unless the fields can contain null as well. Fortunately, the nullable modifier is designed to handle such a scenario specifically.

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

}