C# Syntax Basics Explained with Examples

Beginner Updated February 11, 2025

🔤 C# Syntax Basics Explained with Examples

🟠 1. Variables and Data Types

int age = 25;
string name = "Alice";
double pi = 3.14;
bool isStudent = true;
char grade = 'A';
Type Description Example
int Whole numbers 42
double Decimal numbers 3.14159
bool Boolean values true, false
char Single character 'X'
string Text "Hello"

🟠 2. Control Flow: if, else, switch

int score = 85;

if (score >= 90)
{
    Console.WriteLine("A");
}
else if (score >= 80)
{
    Console.WriteLine("B");
}
else
{
    Console.WriteLine("C or below");
}

🟠 3. Loops: for, while, foreach

// For loop
for (int i = 1; i <= 5; i++)
{
    Console.WriteLine("Count: " + i);
}

// While loop
int j = 1;
while (j <= 5)
{
    Console.WriteLine("While Count: " + j);
    j++;
}

// Foreach loop
string[] fruits = {"Apple", "Banana", "Cherry"};
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

🟠 4. Methods (Functions)

static int Add(int a, int b)
{
    return a + b;
}

int result = Add(5, 3);
Console.WriteLine(result); // Output: 8