In any programing language including C#, variables are the memory space in computer where data can be stored. A variable in C# programming is defined by three main features: name, type and value (optional). Let us take an example:
int var = 1;
In above example, var is the name of variable, int is the type of variable var and 1 is the value stored in memory location.
Rules for Naming Variable
- Variable name can have letters( both uppercase and lowercase ), digits (0 – 9) and underscore ‘_’.
- The name of variable should not be a keyword. For example: for is an invalid name for variable because for is used for defining loop. If you want to use keyword as a variable name, ‘@’ prefix should be before it. For example: for is an invalid variable but @for is valid variable name.
- Variable name shouldn’t start with a digit.
Valid variable name examples: age, FIRST, last_name, first1, _class, @int etc.
Invalid variable name examples: 1, char, 123date etc. are invalid.
Variable Declaration in C#
To declare a variable, we must specify its type and give a name to it. We can also initialize the variable in same line but it’s optional. The syntax for declaring variable is,
<data type> <variable name> [=<value>];
Some examples of variable declaration are:
int a; char b, c; int age = 25;
Now, let us look how values can be assigned to a variable. Assigning a value to a variable is a process of storing values to a memory location of that variable. Values can be assigned to a variable with the help of ‘=’ operator. Syntax for variable assignment is:
<variable name> = <value>;
It can also be done in declaration line as well, which we already discuss above.
<data type> <variable name> = <value>;
Some examples of assigning values are:
name = "Saurav Shrestha"; age = 21; int a = 1; float b = 1.1, c = 2.2;
Note: A variable should be declared before it is defined.
We can initialize values by accepting them from users as well but remember, variable should be declared before it. Console.ReadLine() and Console.Read() can be used to accept the data from user. Example:
int a = Console.Read(); num = Convert.ToInt32(Console.ReadLine());
Default Value of a Variable if not Initialized
If we do not assign any value to a variable then default value is assigned according to its data type. Default values of some data types are listed below:
Data Type | Default Value |
---|---|
bool | false |
byte | 0 |
char | ‘u0000’ |
decimal | 0.0m |
double | 0.0d |
float | 0.0f |
int | 0 |
long | 0L |
sbyte | 0 |
short | 0 |
uint | 0u |
ulong | 0u |
ushort | 0 |
string | null |
object | null |