Variables are one of the first concepts every C# developer learns because nearly every program relies on them. Whether you’re storing a user’s name, calculating a total, or keeping track of a game’s score, variables provide a way to store and manipulate data.
In this guide, you’ll learn what variables are, how to declare and initialize them, naming rules and conventions, common data types, scope, constants, type inference with var, and the different categories of variables defined by the C# language specification.
What Is a Variable?
A variable is a named storage location in memory that holds a value. Every variable has:
- A name (identifier)
- A data type
- A value
The value stored in a variable can usually change during the execution of a program, which is why it is called a variable.
For example:
int age = 25;
Here:
intis the data type.ageis the variable name.25is the initial value.
Whenever the program uses age, it retrieves the value currently stored in that variable.
Why Do We Use Variables?
Variables make programs flexible and reusable.
Instead of writing:
Console.WriteLine(25);
You can write:
int age = 25;
Console.WriteLine(age);
Later, if the value changes, only the variable needs to be updated.
age = 26;
Console.WriteLine(age);
Variables allow programs to:
- Store information
- Perform calculations
- Keep track of application state
- Accept user input
- Produce dynamic output
Variables and Expressions
An expression can either contain fixed values or variables.
For example:
10 + 5
always produces the same result.
However,
x + 5
depends on the current value of x.
int x = 10;
Console.WriteLine(x + 5); // 15
x = 20;
Console.WriteLine(x + 5); // 25
This flexibility is one of the main reasons variables exist.
Declaring Variables
Before using a variable, it must be declared.
The syntax is:
dataType variableName;
Example:
int age;
string name;
double salary;
At this point, the variables exist but may not yet contain meaningful values (especially local variables, which must be assigned before use).
Initializing Variables
Initialization means assigning the first value to a variable.
int age = 25;
You can also initialize a variable later.
int age;
age = 25;
Both approaches are valid.
Declaring Multiple Variables
You can declare multiple variables of the same type.
int x, y, z;
You can also initialize them immediately.
int x = 10, y = 20, z = 30;
Assigning Values
Variables can receive new values at any time.
int score = 100;
score = 150;
score = score + 50;
Final value:
200
The assignment operator (=) stores the value on the right into the variable on the left.
Common C# Data Types
Every variable has a type.
Some of the most common types are:
| Data Type | Description | Example |
|---|---|---|
int | Whole numbers | 10 |
long | Large whole numbers | 9000000000 |
float | Single-precision decimal | 5.4f |
double | Double-precision decimal | 3.14159 |
decimal | High-precision decimal | 19.99m |
char | Single character | ‘A’ |
string | Text | “Hello” |
bool | True or false | true |
Example:
int age = 30;
double price = 19.99;
char grade = 'A';
bool isLoggedIn = true;
string name = "Alice";
Variable Naming Rules
Variable names (identifiers) must follow C# syntax rules.
A variable name:
- Can contain letters, digits, and underscores
- Cannot begin with a digit
- Cannot contain spaces
- Cannot be a C# keyword
- Is case-sensitive
Valid names:
firstName
totalPrice
studentAge
_counter
Invalid names:
1age
first name
class
total-price
Naming Conventions
Although C# allows many names, developers follow conventions.
Local variables typically use camelCase.
Good:
studentName
totalAmount
minutesRemaining
Poor:
x
abc
temp123
Choose descriptive names that clearly communicate the variable’s purpose.
Variable Scope
A variable is only accessible within the part of the program where it is declared.
Example:
{
int number = 5;
Console.WriteLine(number);
}
This works.
However:
{
int number = 5;
}
Console.WriteLine(number);
produces an error because number is outside its scope.
Local Variables
Variables declared inside a method are called local variables.
void Display()
{
int age = 20;
Console.WriteLine(age);
}
They exist only while the method executes.
Type Inference with var
C# allows the compiler to infer the variable’s type using the var keyword.
var name = "Alice";
var age = 30;
var price = 19.95;
The compiler determines the types:
name -> string
age -> int
price -> double
Important points:
vardoes not create a dynamically typed variable.- The type is determined at compile time.
- Once inferred, the type cannot change.
For example:
var age = 25;
age = 30; // OK
age = "John"; // Error
The compiler knows age is an int.
Implicitly Typed Variables
Variables declared with var must be initialized immediately.
This is valid:
var count = 5;
This is not:
var count;
The compiler cannot infer the type without an initial value.
Default Values
Some variables automatically receive default values.
For example, fields in classes are automatically initialized.
| Type | Default Value |
|---|---|
| int | 0 |
| double | 0.0 |
| bool | false |
| char | ‘\0’ |
| string | null |
Local variables are different—they must be assigned before being read.
int number;
Console.WriteLine(number); // Error
Assigning a value first fixes the issue.
int number = 10;
Console.WriteLine(number);
Constants
Sometimes a value should never change.
Use const.
const double Pi = 3.14159265359;
Trying to assign another value later causes a compile-time error.
Pi = 4.0;
Readonly Fields
For class fields that should be assigned only during construction, use readonly.
class Person
{
public readonly string Name;
public Person(string name)
{
Name = name;
}
}
Unlike const, a readonly field can be assigned in a constructor.
Variables vs Constants
Variables:
- Can change value.
- Are used for changing data.
Constants:
- Cannot change after initialization.
- Are used for fixed values like mathematical constants or configuration values.
Variable Categories in C#
The C# language specification groups variables into several categories based on where they exist and how they behave.
Static Variables
Static variables belong to the class itself rather than to an individual object.
class Counter
{
public static int Count;
}
There is only one copy shared by all instances of the class.
Instance Variables
Instance variables belong to an object.
class Student
{
public string Name;
}
Each object has its own copy.
Array Elements
Each position inside an array is considered its own variable.
int[] numbers = { 10, 20, 30 };
numbers[1] = 50;
Here, numbers[1] is an array element variable.
Value Parameters
A normal method parameter receives a copy of the supplied value.
void Print(int number)
{
Console.WriteLine(number);
}
Changing number inside the method does not affect the original variable.
Reference Parameters (ref)
Reference parameters refer to the original variable.
void Increase(ref int value)
{
value++;
}
Changes affect the caller’s variable.
Output Parameters (out)
Output parameters are used to return additional values.
bool TryGetAge(out int age)
{
age = 25;
return true;
}
The called method is responsible for assigning a value before returning.
Input Parameters (in)
Input parameters pass arguments by reference but prevent the method from modifying them.
void Display(in int value)
{
Console.WriteLine(value);
}
This can improve efficiency for large value types while preserving immutability.
Local Variables
Local variables are declared inside methods, loops, or blocks.
void Calculate()
{
int total = 0;
}
They exist only within their scope.
Best Practices
When working with variables:
- Use descriptive names.
- Initialize variables before using them.
- Keep variable scope as small as possible.
- Use
varwhen the type is obvious. - Prefer meaningful names over abbreviations.
- Use
constfor values that never change. - Use
readonlyfor immutable object fields. - Choose the most appropriate data type for the stored value.
Summary
Variables are the foundation of every C# application. They provide named storage for data, allowing programs to remember information, perform calculations, and respond to user input. Understanding how to declare, initialize, update, and organize variables is essential before moving on to more advanced topics such as methods, classes, collections, and object-oriented programming.
As you continue learning C#, you’ll encounter variables in nearly every feature of the language. Mastering them early will make the rest of your programming journey significantly easier.