Variable Initialization
Variable initialization refers to assigning a value to a variable at the time of declaration. In C#, variables must be initialized before they are used in expressions or calculations.
Key Concepts
- Variables must be initialized before they can be used.
- Initialization can occur at the time of declaration or later.
- Uninitialized variables cannot be used and will result in a compilation error.
Example of Variable Initialization
Code Example
// Initialize a variable at the time of declaration
int x = 5;
// Declare without initialization, then assign a value
int y;
y = 10;
// Output the values to the console
Console.WriteLine($"x = {x}, y = {y}");
Output:
x = 5, y = 10
Code Explanation: The variable x
is initialized at the time of declaration, while y
is declared first and assigned a value later. Both values are printed to the console.
Output Explanation: The program prints the values x = 5
and y = 10
after they are initialized.