Variables in C#: Types of Variables with Examples

Understand what variables are in C#, the different types of variables based on scope and data type, and see clear examples of each.

What is a Variable?

A variable in C# is a named storage location in memory used to hold a value that can change during program execution. Every variable has a data type that determines what kind of value it can store.

Value Type Variables

Value type variables, such as int, float, bool, and struct, store their data directly in memory and are copied by value whenever assigned to another variable or passed to a method.

Reference Type Variables

Reference type variables, such as classes, arrays, and strings, store a reference (memory address) to the actual data, meaning multiple variables can point to and modify the same underlying object.

Local, Instance, and Static Variables

Beyond data type, variables can be categorized by where they're declared: local variables exist inside methods, instance variables belong to individual objects, and static variables are shared across all instances of a class.

Conclusion: A solid grasp of variable types, both in terms of data type and category, is fundamental to writing correct and predictable C# programs, especially when it comes to understanding how data is copied versus shared.

Declaring and Initialising Variables

A variable declaration names a type, then the variable, and optionally a starting value:

int age = 25;
double price = 499.99;
bool isActive = true;
char grade = 'A';
string city = "Noida";

var count = 10;        // compiler infers int
const int MaxUsers = 100;   // value fixed at compile time

The var keyword does not make the variable "untyped". The compiler works out the type from the value on the right, and the type cannot change afterwards. Use it when the type is obvious from the line itself. A const must be assigned when declared and can never change, while a readonly field can be set once in a constructor.

C# also requires local variables to be assigned before they are read. This line will not compile:

int total;
Console.WriteLine(total);   // error: use of unassigned local variable

Fields, on the other hand, automatically get a default value: 0 for numbers, false for bool and null for reference types.

Worked Example: Value Copy vs Shared Reference

struct Point { public int X; }
class Box { public int Size; }

Point p1 = new Point { X = 1 };
Point p2 = p1;     // full copy
p2.X = 50;
Console.WriteLine(p1.X);   // 1

Box b1 = new Box { Size = 1 };
Box b2 = b1;       // copies the reference only
b2.Size = 50;
Console.WriteLine(b1.Size);   // 50

The struct behaves like a photocopy, so changing the copy leaves the original alone. The class behaves like two people holding the same key to one room. Strings are a special case: they are reference types, but they are immutable, so any "change" creates a new string and the other variable is unaffected.

Scope and Lifetime in One Class

class Counter
{
    static int totalCreated = 0;   // shared by all objects
    int clicks = 0;                // one per object

    public Counter() { totalCreated++; }

    public void Click()
    {
        int step = 1;              // exists only during this call
        clicks += step;
    }
}

Every Counter has its own clicks, but they all share one totalCreated. The local step is created when Click starts and disappears when it ends. A variable declared inside a block such as an if or loop is only visible inside that block.

Nullable Types, Naming Rules and Pitfalls

Value types cannot normally hold null. Add a question mark to allow it: int? discount = null;. Use discount ?? 0 to supply a fallback value. With nullable reference types enabled in a project, string? marks a string that may be null, and the compiler warns when you use it without a check.

Naming conventions: local variables and parameters use camelCase (orderTotal), while constants and public members use PascalCase. Names must start with a letter or underscore and cannot be a keyword unless prefixed with @.

Mistakes to watch for

  • Expecting a struct passed to a method to be changed by that method.
  • Using var where the type is unclear, such as var result = GetData();, which hurts readability.
  • Making a field static by accident, so all objects unexpectedly share its value.
  • Storing money in double; use decimal to avoid rounding surprises.

Ready to Master C# Programming Course?

Join Uncodemy's hands-on training program with expert mentors and real-world projects.