C# Variables

Variables are containers for storing data values. In C#, every variable has a type that decides what kind of data it can hold, so learning how to declare and use variables is one of the very first steps in writing real programs.

What Is a Variable?

A variable is a named piece of memory that holds a value you can read and change while your program runs. Think of it as a labelled box: the label is the variable name and the contents are the value. Because C# is a strongly typed language, you must tell the compiler what kind of value the box will hold when you create it.

To create a variable you write the type, then a name, and then optionally assign a value with the equals sign. The pattern looks like this: type variableName = value;

Declaring and using a variable

string greeting = "Hello";
int age = 25;

Console.WriteLine(greeting);   // Outputs: Hello
Console.WriteLine(age);        // Outputs: 25

Common Variable Types

You will use a handful of types constantly. Each one is designed for a specific kind of data, and picking the right one makes your code clearer and safer.

TypeStoresExample value
intWhole numbers100
doubleDecimal numbers19.99
charA single character'A'
stringA sequence of characters"Hyring"
boolTrue or falsetrue

Declaring, Assigning, and Changing

You can declare a variable first and assign a value later. You can also change the value of a variable as many times as you like, as long as the new value matches the variable's type. The most recent value is the one that is used.

Reassigning a value

int score = 10;
Console.WriteLine(score);   // Outputs: 10

score = 42;                 // change the value
Console.WriteLine(score);   // Outputs: 42

Naming Rules and the var Keyword

Variable names can contain letters, digits, and underscores, but they cannot start with a digit and cannot be a reserved C# keyword. By convention, C# developers use camelCase for local variables, such as firstName or totalPrice. C# also lets you use the var keyword, which asks the compiler to figure out the type from the value on the right side.

Using var for implicit typing

var city = "Bengaluru";   // compiler infers string
var year = 2026;          // compiler infers int

Console.WriteLine(city);
Console.WriteLine(year);
Note: You can only use var when you assign a value at the same time, because the compiler needs something to infer the type from. 'var total;' will not compile.

Exercise: C# Variables

What must you provide when declaring a variable with an explicit type?