C# Variables
A variable is a named location in memory used to store a value. In C#, every variable must be declared with a specific type before it can be used.
Variable names must start with a letter or underscore, can contain digits, and cannot be a reserved keyword. Choosing clear variable names makes your code much easier to read.
type name = value;Declaring and initializing
A declaration reserves memory of the right type, such as `int age;`. You can also initialize a variable with a value at the same time, like `int age = 25;`.
Naming rules
Names are case-sensitive and can include letters, digits and underscores, but cannot start with a digit. Avoid C# keywords like int, class or for as variable names.
using System;
class Program {
static void Main() {
int age = 25;
double price = 9.99;
Console.WriteLine(age + " " + price);
}
}25 9.99Two variables of different types are declared, initialized and printed.
using System;
class Program {
static void Main() {
int x, y;
x = 5;
y = 10;
Console.WriteLine("Sum: " + (x + y));
}
}Sum: 15Multiple variables of the same type can be declared on one line, then assigned separately.
Key points
- Every variable in C# has a fixed, declared type.
- Variables can be declared and initialized in one statement.
- Names are case-sensitive and cannot start with a digit.
- The `var` keyword lets the compiler infer the type from the value.
