A variable in C# is a named memory location used to store data during program execution. The stored value can be accessed, modified, and reused throughout the program.
Each variable consists of three components:
- Name: Identifier used to reference the variable.
- Type: Specifies the type of data the variable can store (e.g., int, char, double).
- Value: The actual data stored in the variable.
using System;
class Program
{
static void Main()
{
// Creating and initializing a variable
int num = 3;
// Accessing the variable
Console.WriteLine(num);
// Updating the value
num = 7;
// Printing updated value
Console.WriteLine(num);
}
}
Output
3 7
Rules for Naming Variables
- Variable names can contain the letters ‘a-z’ or ’A-Z’ or digits 0-9 as well as the character ‘_’.
- Variable names cannot start with a digit.
- The name of the variable cannot be any C# keyword say int, float, null, string, etc.
Variable Declaration
Declaration means defining the data type and name of a variable. At this stage, the variable is created but no value is assigned.
dataType variableName;
Example:
int x;
double price;
char grade;
Here:
- int, double, and char are data types.
- x, price, and grade are variable names.
Variable Initialization
Initialization means assigning a value to a variable after it has been declared. Example:
int x;
x = 5;
In this example, the variable x is declared first and later assigned the value 5.
A variable can also be declared and initialized in a single statement.
int y = 7;
- y is declared as an integer.
- The value 7 is assigned at the same time.
There are two basic ways for initialization as mentioned below:
1. Compile Time Initialization
In compile-time initialization, the value of the variable is assigned when the program is written. The value remains fixed during execution. Example:
using System;
class Program
{
static void Main()
{
int x = 32;
int y = 0;
Console.WriteLine("Value of x is " + x);
Console.WriteLine("Value of y is " + y);
}
}
Output
Value of x is 32 Value of y is 0
Here, the values of x and y are known before the program runs.
2. Run Time Initialization
In run-time initialization, the value of the variable is assigned during program execution. The value may come from user input, function calls, or program logic. Example:
using System;
class Program
{
static void Main()
{
Console.Write("Enter a number: ");
int num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Value of num is " + num);
}
}
Input:
Enter a number: 45
Output:
Value of num is 45
Explanation: Console.ReadLine() reads input from the user and the entered value is stored in the variable num.