A variable stores data. You must tell C# what type of data it holds.
int age = 21; // Whole numbers
string name = "Kunal"; // Text
double price = 99.99; // Decimals
bool isPaid = true; // True or false
The Big 4 Types
Type
Example
Real use
int
21
Age, quantity, ID
double
99.99
Price, weight, rating
string
"Kunal"
Name, email, address
bool
true
Is logged in? Is admin?
Shortcut: var
var city = "Mumbai"; // C# knows this is string
Deep Dive: All Value Types
Choose the smallest type that fits your data to save memory.
Type
Size
Range
When to use
byte
1 byte
0 to 255
Age if max 255, RGB color values
short
2 bytes
-32K to 32K
Year, small counts
int
4 bytes
-2B to 2B
Default choice for whole numbers
long
8 bytes
Huge numbers
File size in bytes, timestamps
float
4 bytes
~7 digits
Game X,Y coordinates. Use 3.14f
double
8 bytes
~15 digits
Scientific calc, default for decimals
decimal
16 bytes
28 digits
Money. Always. Use 99.99m
char
2 bytes
Single char
'A', '$'. Note single quotes
Real Example: E-commerce Product
string productName = "iPhone 15";
int stockCount = 50; // int is fine, won't exceed 2 billion
decimal price = 79999.00m; // decimal for money. Note the 'm'
double rating = 4.7; // double for average rating
bool isAvailable = stockCount > 0;
char currencySymbol = 'โน'; // Single character
Type Casting: Converting Types
int num = 10;
double result = num; // Implicit: safe. int fits in double. result = 10.0
double pi = 3.14;
int whole = (int)pi; // Explicit: you might lose data. whole = 3
Constants: const
Value that never changes. Must be set when declared.
const double PI = 3.14159;
const string CompanyName = "DevFix";
// PI = 3.14; // Error! Cannot change const
Gotcha #1:decimal price = 99.99; fails. Compiler thinks 99.99 is double. Fix: 99.99m Gotcha #2:int / int = int. So 5 / 2 gives 2, not 2.5. Use 5.0 / 2 or 5 / 2.0 for decimals.
Quick Check ๐ง
Q: You need to store the price of a product โน1,999.99. Which is best?
No comments yet. Be the first to share your thoughts!