Lesson 3 of 24

In progress

Course progress

C# and .NET

Variables, types and var

Value and reference types, the numeric types that matter, decimal for money, and when var helps rather than hides.

C# is statically typed, with a distinction that matters from the first day: value types hold their data directly, reference types hold a reference to an object.

What you will learn

  • Choose among the numeric types and use decimal for money.
  • Understand value versus reference semantics.
  • Use var, const and readonly deliberately.

The common types

int count = 42;               // 32-bit integer
long big = 9_000_000_000L;    // 64-bit
double ratio = 0.5;           // binary floating point
decimal price = 1299.50m;     // base-10, for money
bool ready = true;
char letter = 'A';
string name = "Ana";

int covers about ±2.1 billion. Use long for timestamps in milliseconds, file sizes and anything that might exceed that. The L and m suffixes mark long and decimal literals; without them, a decimal constant is a double.

double is fine for measurements and graphics. decimal is the right type for money because it represents decimal fractions exactly, at the cost of being slower and having a smaller range. A price computed in double will eventually show 1299.4999999999998.

decimal arithmetic also needs care with division: 1m / 3m produces a rounded result with 28 significant digits. Round at the boundary where money becomes visible, with Math.Round(value, 2, MidpointRounding.AwayFromZero) if the business rounds halves up.

Value and reference types

int a = 5;
int b = a;
b = 9;
Console.WriteLine(a);   // 5, copied
var listA = new List<int> { 1, 2 };
var listB = listA;
listB.Add(3);
Console.WriteLine(listA.Count);   // 3, shared

Structs and primitives are value types: assignment copies the value. Classes are reference types: assignment copies the reference, so both variables point at the same object.

string is a reference type with value-like behaviour: it is immutable, and == compares content. That combination makes it safe to treat strings as values even though they are objects.

record struct and readonly struct let you define your own value types. They are useful for small, immutable values such as coordinates or money amounts.

var

var total = 1299.50m;              // decimal
var names = new List<string>();    // List<string>
var lookup = new Dictionary<int, string>();

var is compile-time inference, not a dynamic type. The variable’s type is fixed once inferred, and the compiler knows it everywhere.

Use it when the right-hand side makes the type obvious, as above. Avoid it when the type is the important information:

IReadOnlyList<string> items = Load();   // the interface is the point
var items2 = Load();                    // hides whether it is a list or an array

Declaring the interface communicates the contract; var communicates nothing.

const and readonly

const int MaxAttempts = 3;
static readonly decimal FreeShippingThreshold = 500m;

const is a compile-time constant: it must be a literal and is copied into every assembly that uses it. Changing a const in a library does not change the value compiled into its callers until they recompile, which is a real deployment hazard for public constants.

readonly is assigned once at runtime, in the declaration or the constructor. Prefer it for values that are fixed per instance or per type but computed, such as a threshold loaded from configuration.

Naming: PascalCase for constants and static readonly fields, camelCase for locals and parameters.

Conversion

int i = 42;
long l = i;              // implicit widening
double d = i;            // implicit, may lose precision for large values
int back = (int)3.99;    // explicit, truncates to 3
int parsed = int.Parse("42");

Widening conversions are implicit. Narrowing needs a cast and can lose data. Convert.ToInt32(3.99) rounds instead of truncating, which is a different behaviour and a common source of off-by-one bugs when mixed with casts.

checked turns silent overflow into an exception:

checked
{
int max = int.MaxValue;
// max + 1 throws OverflowException
}

By default, integer overflow wraps. Use checked in financial or size calculations where a wrap would be a bug.

Default values

int zero;            // 0
bool flag;           // false
string? text;        // null

Local variables must be assigned before use, so the defaults matter mainly for fields. A non-nullable reference field is null at runtime even though the compiler treats it as non-null, which is why nullable annotations plus constructor initialisation matter.

Choosing a type

  • Whole counts: int, or long when large.
  • Money: decimal, always.
  • Measurements: double.
  • Text: string.
  • A flag: bool.
  • A fixed set of options: an enum.

Getting the type right at the start avoids a migration later, because changing a type means touching every signature that carries it.

Using double for a price and formatting it for display. The value drifts, totals disagree by a paisa, and the bug appears only after enough transactions. Use decimal and the unit suffix in the name.

Declare variables for a product name, a price in rupees as decimal, a stock count and an in-stock flag. Print them with a total value of stock, formatted to two decimals.

Show solution
string name = "Desk lamp"; decimal price = 1299.50m; int stock = 12; bool inStock = stock > 0; decimal stockValue = price * stock; Console.WriteLine($"{name}: {stock} units, {stockValue:F2} total, in stock: {inStock}");

decimal keeps the multiplication exact, and F2 formats two decimals without changing the value. The flag is derived from the count rather than stored separately, so the two cannot disagree.

Recap

  • int for counts, long for large numbers, decimal for money, double for measurements.
  • Value types copy on assignment; reference types share the object.
  • var is inference, not dynamism; use it when the right-hand side is unambiguous.

Next, strings and the methods that make text handling safe.

Is string a value type?
No, but it is immutable and compares by content, so it behaves like one in most code.
Why does 0.1 + 0.2 not equal 0.3?
Binary floating point cannot represent those fractions exactly. Use `decimal` for money and compare doubles with a tolerance.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.