How to declare and initialize a variable in C#

 A concept of a variable

A variable is something which we can change the value of . In C#, a variable is a storage area in memory which holds the particular value in it. A variable name is prefixed with the data type. The data type of the variable decides what type of value and what range of values can be stored in that variable.


Declaring and initializing  a variable.

The below code declares the variable of Integer data type 

int age=22; 

 'age' is a name of a variable. The compiler will allocate some memory to this variable and store the value 22 in it. The 'int' is a data type of a variable. It means we can store only numbers in this variable. You will learn about the Data types in the next post.

Print the value of the variable on console using below code.

Console.WriteLine(age);

Declaring multiple variables

You can declare multiple variables on the same line by separating them with comma(,). These variables must be of same data type

int age,id,salary

A variable must be assigned a value before trying to access it. If you try to access variable without assigning a value, compiler will throw compile time exception.

If you declare and initialize a variable at the top and later in the program you assign another value to the same variable, the new value will replace the old value. For example

First initialization -  int age=20;

Initialize same variable again - age=33;

The variable age will now contain 33 value.


Memory allocation

When the variable is declared, the compiler allocated some memory to the variable. The memory allocated depends on the data type. Basically compiler allocates memory to variable on the stack. A Stack is a Last In First Out (LIFO) data structure. You will learn about the Data structures in upcoming posts.











Comments

Popular posts from this blog

Implicitly typed keyword - var in C#

Classes and objects in C#

Data types in C#