Variables & Data Types

C# · Lesson 5 of 31 6 min read Updated

A program spends most of its time working with values: marks, prices, names, dates, yes/no answers. A variable is a named box that holds one value. Because C# is statically typed, every box also has a type that decides what kind of value it can hold and what you can do with it.

In this lesson you will declare variables, meet the built-in types you will use every day, let the compiler work out types with var, and convert values from one type to another safely.

Declaring variables

A declaration has a type, a name and (usually) a starting value:

C#
string name = "Priya";
int age = 19;
double heightMetres = 1.62;
bool isHosteller = true;
char section = 'B';
decimal feePaid = 45500.50m;

Console.WriteLine($"{name}, {age} years, {heightMetres} m");
Console.WriteLine($"Hosteller: {isHosteller}, Section: {section}");
Console.WriteLine($"Fee paid: Rs {feePaid}");

age = 20; // assign a new value later
Console.WriteLine($"Next year {name} will be {age}");
Output
Priya, 19 years, 1.62 m
Hosteller: True, Section: B
Fee paid: Rs 45500.50
Next year Priya will be 20

Notice a few details:

  • Text (string) goes in double quotes; a single character (char) goes in single quotes.
  • A decimal value needs the m suffix, as in 45500.50m. The decimal keeps the trailing zero, so it prints 45500.50.
  • bool values print as True and False with a capital letter.
  • After declaring a variable, you change its value with = alone. Writing the type again would declare a second variable with the same name, which is an error.

The built-in types

TypeHoldsRange or precisionExample
intWhole numbers (32-bit)about -2.1 billion to 2.1 billionint seats = 72;
longBig whole numbers (64-bit)about ±9.2 quintillionlong views = 8_200_000_000;
doubleNumbers with decimalsabout 15-17 significant digitsdouble km = 1288.5;
floatSmaller decimal numbersabout 6-9 digitsfloat temp = 36.6f;
decimalExact decimal numbers, money28-29 significant digitsdecimal price = 1299.00m;
booltrue or falsebool paid = false;
charOne characterany UTF-16 code unitchar grade = 'A';
stringTextany lengthstring city = "Pune";

Use int for counts, double for measurements and science, decimal for money, and long only when numbers may pass two billion. You can put underscores inside number literals to make them readable, even in the Indian lakh-crore style:

C#
int lakh = 1_00_000;
int crore = 1_00_00_000;
long worldPopulation = 8_200_000_000;

Console.WriteLine(lakh);
Console.WriteLine(crore);
Console.WriteLine(worldPopulation);
Console.WriteLine(int.MaxValue);
Output
100000
10000000
8200000000
2147483647

The underscores are ignored by the compiler. int.MaxValue is the largest value an int can hold.

var and const

When the type is obvious from the value, you can write var and let the compiler infer it. The variable is still strongly typed: the type is fixed at compile time and can never change.

C#
var city = "Kochi";
var trains = 12;
var distance = 1288.5;
const int SeatsPerCoach = 72;

Console.WriteLine(city.GetType());
Console.WriteLine(trains.GetType());
Console.WriteLine(distance.GetType());
Console.WriteLine(SeatsPerCoach * 18);
Output
System.String
System.Int32
System.Double
1296

GetType() shows the real .NET type name: string is a short alias for System.String, int for System.Int32 and double for System.Double. var needs a starting value, so var x; is an error.

A const is a value that can never change after compilation. Use it for fixed facts such as seats per coach or the number of months in a year. Trying to assign to a constant later is a compile error.

Converting between types

Sometimes you need a value of one type as another type. C# allows implicit conversions only when no information can be lost, for example int to double. When data might be lost, you must ask for an explicit conversion (a cast) by writing the target type in brackets.

C#
int marks = 87;
double asDouble = marks;            // implicit: safe
double price = 249.99;
int cut = (int)price;               // explicit cast: the fraction is cut off
int fromText = int.Parse("350");    // text to number
string back = fromText.ToString();  // number to text

Console.WriteLine(asDouble);
Console.WriteLine(cut);
Console.WriteLine(fromText + 50);
Console.WriteLine(back + 50);
Console.WriteLine(Convert.ToInt32(249.5));
Console.WriteLine(Convert.ToInt32(248.5));
Output
87
249
400
35050
250
248

Look carefully at these results:

  • (int)249.99 gives 249: a cast truncates, it does not round.
  • fromText + 50 is number addition, but back + 50 joins text, giving "35050".
  • Convert.ToInt32 rounds, and when a value is exactly halfway it rounds to the nearest even number, so 249.5 becomes 250 but 248.5 becomes 248. This is called banker's rounding.

double vs decimal: why money needs decimal

double stores numbers in binary, and many decimal fractions such as 0.1 cannot be stored exactly. Tiny errors appear:

C#
double a = 0.1 + 0.2;
decimal b = 0.1m + 0.2m;

Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(a == 0.3);
Console.WriteLine(b == 0.3m);
Output
0.30000000000000004
0.3
False
True

For a physics formula, an error in the 17th digit does not matter. For a shop bill or a bank balance, it does. Always use decimal for money.

Common mistakes

  • Forgetting the m suffix. decimal price = 99.5; fails with CS0664: Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type. Write 99.5m. Similarly, float needs f.
  • Storing a decimal number in an int. int x = 3.7; fails with CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?).
  • Using a variable before giving it a value. int total; Console.WriteLine(total); fails with CS0165: Use of unassigned local variable 'total'.
  • Expecting a cast to round. (int)9.99 is 9. Use Math.Round or Convert.ToInt32 when you want rounding.
  • Using double for money. Small binary errors add up over thousands of bills. Use decimal.

Key points

  • A variable has a type, a name and a value: int age = 19;.
  • Common types: int, long, double, decimal, bool, char and string.
  • var lets the compiler infer the type, but the type is still fixed; const values never change.
  • Implicit conversions are allowed only when safe; use a cast such as (int) otherwise, and remember casts truncate.
  • int.Parse turns text into a number and ToString() turns a value into text.
  • Use decimal (with the m suffix) for money, because double cannot store 0.1 exactly.

Exercise

Write a program for a mobile shop in Lucknow. Store the phone model (string), the price 14999.00 (decimal), the quantity in stock 25 (int), whether it supports 5G (bool) and its rating 4.3 (double). Print each value on its own line with a label, then print the total stock value (price times quantity). Finally, convert the rating to an int with a cast and print it.

Show solution
C#
string model = "Galaxy M35";
decimal price = 14999.00m;
int stock = 25;
bool has5G = true;
double rating = 4.3;

Console.WriteLine($"Model: {model}");
Console.WriteLine($"Price: Rs {price}");
Console.WriteLine($"In stock: {stock}");
Console.WriteLine($"5G: {has5G}");
Console.WriteLine($"Rating: {rating}");
Console.WriteLine($"Stock value: Rs {price * stock}");
Console.WriteLine($"Rating as int: {(int)rating}");
Output
Model: Galaxy M35
Price: Rs 14999.00
In stock: 25
5G: True
Rating: 4.3
Stock value: Rs 374975.00
Rating as int: 4

Multiplying a decimal by an int gives a decimal, which keeps the two decimal places. The cast (int)rating cuts off the .3.

Quick Quiz

1. Which type should you use to store a bank balance?

2. What does (int)7.9 evaluate to?

3. What is printed by var x = 12; Console.WriteLine(x.GetType());?

4. Why does decimal p = 10.5; fail to compile?

Learn C# with a mentor

Free lessons get you started. Our Programming & Software Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call