C# Variables, Data Types and Input
A variable stores a value, like a name or a price, under a name you choose.
Declaring Variables
Write the type, the name and the value:
Example
string name = "Sana";
int age = 23;
double height = 5.4;
char grade = 'A';
bool isEnrolled = true;
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(height);
Console.WriteLine(grade);
Console.WriteLine(isEnrolled);Sana 23 5.4 A True
Notice that C# prints bool values as True and False, with a capital letter.
Common Data Types
| Type | Stores | Example |
|---|---|---|
int | Whole numbers | int seats = 40; |
long | Very large whole numbers | long views = 9000000000; |
double | Decimal numbers | double km = 12.75; |
decimal | Exact decimals, for money | decimal fee = 4999.99m; |
char | One character | char initial = 'S'; |
bool | true or false | bool paid = false; |
string | Text | string city = "Karachi"; |
Use decimal for money. double can show tiny rounding errors (0.1 + 0.2 is not exactly 0.3), but decimal stores values like 0.1 exactly. Add m after decimal values.
String Interpolation
Put $ before a string and write variables inside { }. This is the cleanest way to mix text and values:
Example
string student = "Ali";
int marks = 87;
decimal fee = 3500.50m;
Console.WriteLine($"{student} scored {marks} marks");
Console.WriteLine($"Fee: Rs {fee}");
Console.WriteLine($"Half marks: {marks / 2.0}");Ali scored 87 marks Fee: Rs 3500.50 Half marks: 43.5
var and const
Example
var city = "Hyderabad"; // the compiler knows it is a string
var count = 5; // the compiler knows it is an int
const int MaxSeats = 30; // can never be changedType Conversion
C# converts small types to bigger ones automatically. Going the other way needs a cast:
Example
int whole = 9;
double d = whole; // automatic: 9
double price = 7.9;
int cut = (int)price; // cast: 7 (decimal part removed)
Console.WriteLine(cut);7
To turn text into a number, use int.Parse, double.Parse or Convert.ToInt32. To turn anything into text, use .ToString().
Reading Input
Console.ReadLine() reads a line typed by the user. It always returns a string, so convert it when you need a number:
Example
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.Write("Enter your age: ");
int age = int.Parse(Console.ReadLine());
Console.WriteLine($"Hello {name}, in 5 years you will be {age + 5}.");Enter your name: Ayesha Enter your age: 19 Hello Ayesha, in 5 years you will be 24.
If the user types something that is not a number, int.Parse throws an error. int.TryParse is a safer choice that you will meet later.
Exercise
Exercise
Which type is the best choice for storing a shop's prices exactly?
