C# Tutorial menu

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

csharp
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);
Output
Sana
23
5.4
A
True

Notice that C# prints bool values as True and False, with a capital letter.

Common Data Types

TypeStoresExample
intWhole numbersint seats = 40;
longVery large whole numberslong views = 9000000000;
doubleDecimal numbersdouble km = 12.75;
decimalExact decimals, for moneydecimal fee = 4999.99m;
charOne characterchar initial = 'S';
booltrue or falsebool paid = false;
stringTextstring 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

csharp
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}");
Output
Ali scored 87 marks
Fee: Rs 3500.50
Half marks: 43.5

var and const

Example

csharp
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 changed

Type Conversion

C# converts small types to bigger ones automatically. Going the other way needs a cast:

Example

csharp
int whole = 9;
double d = whole;          // automatic: 9
double price = 7.9;
int cut = (int)price;      // cast: 7 (decimal part removed)
Console.WriteLine(cut);
Output
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

csharp
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}.");
Output
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?

Learn C# with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp