Variables in C# are named storage locations used to hold data while a program runs. A variable can store a number, character, text, Boolean value, object reference, or another type of data. Every useful C# program uses variables because programs need to remember values, calculate results, read input, pass data to methods, and update state during execution.
C# is a strongly typed language, so every variable has a type. The type decides what kind of value the variable can store and what operations can be performed on it. For example, an int variable can store whole numbers, a string variable can store text, and a bool variable can store either true or false.
What Is a Variable in C#?
A variable is a name given to a value stored in memory. Instead of writing the same value repeatedly, you can store it in a variable and use the variable name whenever needed.
int age = 21;
string name = "Alex";
Here, age stores an integer value and name stores text. The variables make the program easier to read and easier to update.
A variable gives a meaningful name to a value that the program needs to use.
Syntax to Declare a Variable in C#
dataType variableName;
Example:
int number;
This declares a variable named number of type int. At this point, the variable exists, but for a local variable, you must assign a value before reading it.
Declaration and Initialization
Declaration means creating the variable. Initialization means giving it an initial value.
int marks; // declaration
marks = 85; // assignment
You can also declare and initialize a variable in one line.
int marks = 85;
This is usually preferred when you already know the starting value.
Example of Variables in C#
using System;
class Program
{
static void Main()
{
string studentName = "Riya";
int age = 20;
double percentage = 87.5;
bool passed = true;
Console.WriteLine(studentName);
Console.WriteLine(age);
Console.WriteLine(percentage);
Console.WriteLine(passed);
}
}
This program creates four variables with different types and prints their values to the console.
Common Variable Types in C#
| Type | Stores | Example |
|---|---|---|
int | Whole numbers | int count = 10; |
double | Decimal numbers | double price = 99.5; |
char | Single character | char grade = 'A'; |
string | Text | string city = "Pune"; |
bool | True or false | bool active = true; |
decimal | High-precision decimal values | decimal salary = 50000.50m; |
The type should match the data. Use int for whole numbers, double for general decimal calculations, decimal for money-like values, string for text, and bool for true or false conditions.
Assigning New Values to Variables
A normal variable can be assigned a new value after it is created, as long as the new value is compatible with the variable type.
int score = 50;
score = 75;
Console.WriteLine(score);
The final output is 75 because the second assignment replaces the previous value.
C# Is Strongly Typed
Once a variable has a type, you cannot store an incompatible value in it.
int age = 25;
// age = "twenty five"; // Error
This is a compile-time error because a string value cannot be assigned to an integer variable. Strong typing helps catch such mistakes before the program runs.
Using var in C#
C# supports the var keyword for local variables. When you use var, the compiler infers the type from the value on the right side.
var number = 10;
var message = "Hello";
var isReady = true;
This does not make C# dynamically typed. The compiler still gives each variable a fixed type. For example, number becomes an int, message becomes a string, and isReady becomes a bool.
var Does Not Mean Any Type
var value = 100;
// value = "text"; // Error
The variable value is inferred as int. After that, it cannot store a string. This is an important difference between var and dynamic.
Constants vs Variables
A variable can change during program execution. A constant cannot be changed after declaration.
const double Pi = 3.14159;
int radius = 5;
Here, Pi should stay fixed, while radius may change depending on the program logic. Use constants for values that should remain the same.
Local Variables in C#
A local variable is declared inside a method, block, loop, or statement body. It can only be used inside that scope.
void ShowAge()
{
int age = 30;
Console.WriteLine(age);
}
The variable age exists only inside ShowAge(). Code outside the method cannot directly access it.
Variable Scope
Scope decides where a variable can be used. A variable declared inside a block is only available within that block and its nested blocks.
if (true)
{
int x = 10;
Console.WriteLine(x);
}
// Console.WriteLine(x); // Error
The second print statement is invalid because x only exists inside the if block.
Fields vs Local Variables
Variables declared inside a class but outside methods are usually called fields. Variables declared inside methods are local variables.
class Student
{
string name; // field
void SetName()
{
string newName = "Aman"; // local variable
name = newName;
}
}
Fields are connected to an object or class, while local variables are temporary values used inside a method or block.
Default Values
Fields automatically get default values if you do not initialize them. Local variables do not allow reading before assignment.
| Type | Default Value |
|---|---|
int | 0 |
double | 0.0 |
bool | false |
char | '\0' |
| Reference types | null |
This difference is important. Even though fields have defaults, it is often better to initialize values clearly so the program intent is easier to understand.
Naming Rules for Variables in C#
- A variable name can contain letters, digits, and underscores.
- A variable name cannot start with a digit.
- A variable name cannot be a C# keyword unless escaped with
@. - C# variable names are case-sensitive.
- Use meaningful names instead of vague names like
a,b, ortempunless the context is very small.
Naming Conventions
Local variables in C# usually use camelCase.
int studentAge = 20;
string firstName = "Neha";
bool isLoggedIn = true;
Good variable names make code easier to read. A name like totalMarks is much clearer than tm for most beginner and application code.
Value Type Variables and Reference Type Variables
Variables in C# can store value types or reference types. A value type variable directly holds its data. Examples include int, double, bool, char, and struct values. A reference type variable stores a reference to an object. Examples include string, arrays, classes, and most objects created with new.
| Category | Examples | Basic Idea |
|---|---|---|
| Value type | int, double, bool, char | Stores the actual value. |
| Reference type | string, arrays, classes | Stores a reference to an object. |
This difference becomes more important when you start passing variables to methods and working with objects. For beginners, the key point is that not every variable stores data in the same way internally, even if the syntax looks similar.
Explicit Type vs var
Both explicit typing and var can be correct. Explicit typing is useful when learning because the type is visible immediately. var is useful when the type is obvious or very long.
int count = 10;
var total = 25;
In this example, both variables are integers. The second one is still strongly typed; the compiler simply inferred the type from the value 25.
Variable Lifetime
Lifetime means how long a variable exists while the program runs. A local variable exists only while its method or block is executing. A field exists as long as the object that owns it exists, or for the whole application lifetime if it is a static field. Understanding lifetime helps prevent wrong assumptions about when values are created, changed, and removed.
Reassignment vs New Variable
Reassignment changes the value stored in an existing variable. Creating a new variable gives a separate name to a separate value. Beginners sometimes reuse one variable for too many different meanings, which makes code harder to read. If a value represents a different idea, create a new well-named variable instead of forcing the old one to do everything.
int price = 500;
int discountedPrice = 450;
Common Mistakes with Variables in C#
- Using a local variable before assigning a value.
- Assigning a value of the wrong type.
- Confusing
varwith dynamic typing. - Using unclear variable names.
- Declaring variables in a scope where they are not available later.
- Using constants for values that actually need to change.
Can a C# variable change its type?
No. Once a variable has a type, it cannot change to another type. You can assign a new compatible value, but the variable type remains fixed.
Is var the same as dynamic in C#?
No. var is resolved at compile time and remains strongly typed. dynamic delays type checking until runtime.
Should beginners use var?
Beginners can use var, but it is better to first learn explicit types clearly. Use var when the type is obvious from the right side and it improves readability.
Best Practices for Variables in C#
- Choose the correct data type for the value.
- Initialize variables before using them.
- Use meaningful names that describe the value.
- Keep variable scope as small as practical.
- Use constants for values that must not change.
- Use
varonly when it keeps the code clear. - Avoid keeping unused variables in the program.
Variables in C# are simple at the surface, but they connect to many important concepts: type safety, memory, scope, fields, constants, object state, and readable code. Once you understand variables properly, the next topics in C# programming become much easier to learn. Clear variable usage also makes debugging much easier.