1. Output & Display Data
In C#, we use the Console class to display text to the user.
// WriteLine prints text and goes to a new line
Console.WriteLine("Hello World!");
// Write prints text on the same line
Console.Write("I am learning ");
Console.Write("C#");
2. Input Data
To get data from the user, use Console.ReadLine(). Remember, it always returns a String.
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Welcome " + name);
// Converting String to Integer
Console.Write("Enter your age: ");
int age = Convert.ToInt32(Console.ReadLine());
3. Basic Numeric Operators
Standard math operators in C#:
| Operator | Meaning | Example |
|---|---|---|
| + | Add | x + y |
| - | Subtract | x - y |
| * | Multiply | x * y |
| / | Divide | x / y |
| % | Modulus | x % y |
4. Conditions (If / Else)
Use if statements to specify a block of code to be executed if a condition is true.
int time = 20;
if (time < 18)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
5. Loops (Iteration)
Loops can execute a block of code as long as a specified condition is reached.
For Loop
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
While Loop
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
6. Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
// Declare an array of strings
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
// Access the first element (Index starts at 0)
Console.WriteLine(cars[0]); // Outputs: Volvo
// Change an element
cars[0] = "Opel";
7. Switch Statement
Use the switch statement to select one of many code blocks to be executed. It's cleaner than many if..else statements.
int day = 4;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
default:
Console.WriteLine("Other day");
break;
}
8. Methods
A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method.
class Program
{
// Define the method
static void MyMethod(string fname)
{
Console.WriteLine(fname + " is a student");
}
static void Main(string[] args)
{
// Call the method
MyMethod("Mahmoud");
MyMethod("Ahmed");
}
}