Variables & Data Types
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:
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}");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
decimalvalue needs themsuffix, as in45500.50m. The decimal keeps the trailing zero, so it prints45500.50. boolvalues print asTrueandFalsewith 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
| Type | Holds | Range or precision | Example |
|---|---|---|---|
int | Whole numbers (32-bit) | about -2.1 billion to 2.1 billion | int seats = 72; |
long | Big whole numbers (64-bit) | about ±9.2 quintillion | long views = 8_200_000_000; |
double | Numbers with decimals | about 15-17 significant digits | double km = 1288.5; |
float | Smaller decimal numbers | about 6-9 digits | float temp = 36.6f; |
decimal | Exact decimal numbers, money | 28-29 significant digits | decimal price = 1299.00m; |
bool | true or false | bool paid = false; | |
char | One character | any UTF-16 code unit | char grade = 'A'; |
string | Text | any length | string 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:
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);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.
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);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.
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));87 249 400 35050 250 248
Look carefully at these results:
(int)249.99gives249: a cast truncates, it does not round.fromText + 50is number addition, butback + 50joins text, giving"35050".Convert.ToInt32rounds, and when a value is exactly halfway it rounds to the nearest even number, so249.5becomes250but248.5becomes248. 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:
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);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
msuffix.decimal price = 99.5;fails withCS0664: Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type. Write99.5m. Similarly,floatneedsf. - Storing a decimal number in an
int.int x = 3.7;fails withCS0266: 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 withCS0165: Use of unassigned local variable 'total'. - Expecting a cast to round.
(int)9.99is9. UseMath.RoundorConvert.ToInt32when you want rounding. - Using
doublefor money. Small binary errors add up over thousands of bills. Usedecimal.
Key points
- A variable has a type, a name and a value:
int age = 19;. - Common types:
int,long,double,decimal,bool,charandstring. varlets the compiler infer the type, but the type is still fixed;constvalues never change.- Implicit conversions are allowed only when safe; use a cast such as
(int)otherwise, and remember casts truncate. int.Parseturns text into a number andToString()turns a value into text.- Use
decimal(with themsuffix) for money, becausedoublecannot 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
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}");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?
decimal stores decimal fractions exactly, which is what money needs.
2. What does (int)7.9 evaluate to?
A cast to int truncates the fractional part; it does not round.
3. What is printed by var x = 12; Console.WriteLine(x.GetType());?
var infers int, whose .NET type name is System.Int32.
4. Why does decimal p = 10.5; fail to compile?
Number literals with a decimal point are double by default; write 10.5m for a decimal.
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
