Click on a topic to expand and learn in detail.
// Hello World
using System;
class Program {
static void Main() {
Console.WriteLine("Hello World!");
}
}
C# is an object-oriented, strongly-typed language mainly used for Windows apps, web apps, and games (Unity).
int age = 25;
double salary = 45000.5;
string name = "Alice";
bool isStudent = true;
Variables store data. C# has types like int, double, string, bool, etc.
// Arithmetic
int sum = 5 + 3;
// Comparison
bool isAdult = age >= 18;
// Logical
bool flag = isAdult && isStudent;
Operators perform calculations, comparisons, or logical operations.
if(age >= 18){
Console.WriteLine("Adult");
}else{
Console.WriteLine("Minor");
}
// Switch
switch(age){
case 18:
Console.WriteLine("Exactly 18");
break;
default:
Console.WriteLine("Other age");
}
Use if-else or switch to control program flow based on conditions.
// for loop
for(int i=0; i<5; i++){
Console.WriteLine(i);
}
// while loop
int j=0;
while(j<5){
Console.WriteLine(j);
j++;
}
// foreach (arrays)
string[] fruits = {"Apple","Banana","Mango"};
foreach(string fruit in fruits){
Console.WriteLine(fruit);
}
Loops repeat code multiple times until a condition is met.
int Add(int a, int b){
return a + b;
}
Console.WriteLine(Add(5,3));
Methods are reusable code blocks that can return values.
class Person {
public string Name;
public int Age;
public void Greet(){
Console.WriteLine("Hello " + Name);
}
}
Person p = new Person();
p.Name = "Alice";
p.Age = 25;
p.Greet();
C# supports OOP concepts: Classes, Objects, Inheritance, Encapsulation, Polymorphism.
// Example: Exception Handling
try {
int x = int.Parse("abc");
} catch(Exception e) {
Console.WriteLine("Error: " + e.Message);
}