Great! Starting from Module 0: Basics - I'll teach you C# from absolute beginning. Even if you know some, this will fill any gaps and ensure strong fundamentals.
MODULE 0: C# BASICS - Complete Guide
1. What is C# and .NET?
// C# = Programming language (pronounced "C sharp")
// .NET = Framework/Runtime that runs C# code
// Think of it like:
// C# is the recipe, .NET is the kitchen and oven
// Key components:
// - CLR (Common Language Runtime) - Runs your code
// - CTS (Common Type System) - All types share common base
// - CLS (Common Language Specification) - Language interop rules
// - BCL (Base Class Library) - Built-in functions (Console, String, etc.)
2. Hello World - Your First Program
// Program.cs file
using System; // Import the System namespace (like importing tools)
namespace MyFirstProgram // Organizes your code (like a folder)
{
class Program // Blueprint for your program
{
static void Main(string[] args) // Entry point (where program starts)
{
Console.WriteLine("Hello, World!"); // Print with new line
Console.Write("Hello "); // Print without new line
Console.Write("World!"); // Output: Hello World!
}
}
}
// Modern C# (C# 9+) allows simpler syntax:
// Console.WriteLine("Hello, World!"); // Top-level statements
3. Variables and Data Types
// Variables - containers for storing data
// Syntax: type variableName = value;
// Integer types (whole numbers)
byte smallNumber = 255; // 0 to 255 (1 byte)
int wholeNumber = 42; // -2B to 2B (4 bytes) - MOST COMMON
long bigNumber = 9_000_000_000L; // Very large (8 bytes)
// Floating point types (decimals)
float price = 19.99f; // 6-9 digits precision (4 bytes)
double pi = 3.14159265359; // 15-17 digits (8 bytes) - DEFAULT
decimal money = 19.99m; // Money/exact (16 bytes)
// Text types
char singleLetter = 'A'; // Single character
string name = "John Doe"; // Multiple characters
// Logical type
bool isActive = true; // true or false
// Date/Time
DateTime today = DateTime.Now; // Current date and time
// Implicit typing (C# 3.0+)
var inferredType = "Hello"; // Compiler figures out it's string
var number = 42; // Compiler figures out it's int
// Type suffixes
float f = 3.14f; // 'f' for float
double d = 3.14; // No suffix needed (default)
decimal m = 3.14m; // 'm' for decimal
long l = 100L; // 'L' for long
uint u = 100U; // 'U' for unsigned
4. Console Input/Output
// OUTPUT
Console.WriteLine("Hello"); // Adds new line at end
Console.Write("Hello"); // No new line
Console.WriteLine($"My name is {name}"); // String interpolation (C# 6+)
Console.WriteLine("My age is " + age); // Concatenation
// Formatting
Console.WriteLine("{0} is {1} years old", name, age); // Placeholders
Console.WriteLine($"Price: {price:C}"); // Currency: $19.99
Console.WriteLine($"Percent: {percent:P}"); // Percent: 75.00%
Console.WriteLine($"Number: {num:N2}"); // Number with 2 decimals: 1,234.56
// INPUT
string input = Console.ReadLine(); // Reads text until Enter
int number = int.Parse(Console.ReadLine()); // Convert to int
bool success = int.TryParse(input, out int result); // Safe conversion
// Read a single character
char key = Console.ReadKey().KeyChar;
char keyInfo = Console.ReadKey(true).KeyChar; // true = hidden from console
// Example - Interactive program
Console.Write("Enter your name: ");
string userName = Console.ReadLine();
Console.Write("Enter your age: ");
int userAge = int.Parse(Console.ReadLine());
Console.WriteLine($"Hello {userName}, you are {userAge} years old!");
5. Comments and Whitespace
// Single line comment - ignored by compiler
/* Multi-line comment
Can span multiple lines
Also ignored */
/// XML comment - creates documentation
/// <summary>
/// This method calculates the sum
/// </summary>
public int Add(int a, int b) => a + b;
// Whitespace is ignored by C# compiler
int x = 10; // Spaces don't matter
int y=10; // Same as above
// But line breaks matter for readability
int result =
10 + 20 + 30; // OK - continues to next line
// Naming conventions
int customerAge; // camelCase - for variables
string customerName;
const int MAX_SIZE = 100; // UPPER_CASE - for constants
string CustomerAddress; // PascalCase - for methods/classes (sometimes)
6. Operators
// ARITHMETIC OPERATORS
int sum = 10 + 5; // Addition = 15
int difference = 10 - 5; // Subtraction = 5
int product = 10 * 5; // Multiplication = 50
int quotient = 10 / 3; // Division = 3 (integer division truncates)
double exact = 10.0 / 3; // Division = 3.3333
int remainder = 10 % 3; // Modulus = 1 (remainder)
// Increment/Decrement
int count = 5;
count++; // count becomes 6 (post-increment)
++count; // count becomes 7 (pre-increment)
count--; // count becomes 6
--count; // count becomes 5
// COMPARISON OPERATORS (returns bool)
bool isEqual = 5 == 5; // true
bool notEqual = 5 != 3; // true
bool greater = 10 > 5; // true
bool less = 3 < 5; // true
bool greaterOrEqual = 5 >= 5; // true
bool lessOrEqual = 3 <= 5; // true
// LOGICAL OPERATORS
bool and = true && true; // AND - true only if both true
bool or = true || false; // OR - true if at least one true
bool not = !true; // NOT - reverses (false)
// ASSIGNMENT OPERATORS
int x = 10; // Basic assignment
x += 5; // x = x + 5 (15)
x -= 3; // x = x - 3 (12)
x *= 2; // x = x * 2 (24)
x /= 4; // x = x / 4 (6)
x %= 2; // x = x % 2 (0)
// NULL OPERATORS (C# 6+)
string name = null;
string result = name ?? "Default"; // Null coalescing - returns "Default"
string text = name?.ToUpper(); // Null conditional - returns null (not error)
// TERNARY OPERATOR (shorthand if-else)
int age = 20;
string status = age >= 18 ? "Adult" : "Minor";
// BITWISE OPERATORS (for low-level operations)
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int andBits = a & b; // 0001 = 1
int orBits = a | b; // 0111 = 7
int xorBits = a ^ b; // 0110 = 6
int notBits = ~a; // 1010 = -6 (two's complement)
int leftShift = a << 1; // 1010 = 10
int rightShift = a >> 1; // 0010 = 2
7. Strings and String Methods
// String creation
string empty = ""; // Empty string
string nullString = null; // Null reference
string whitespace = " "; // Space character
string sentence = "Hello World"; // Normal string
// Escape sequences
string withQuote = "He said \"Hello\""; // He said "Hello"
string newLine = "Line1\nLine2"; // Line1 Line2 on new line
string backslash = "C:\\Windows\\System"; // C:\Windows\System
string verbatim = @"C:\Windows\System"; // Verbatim string - ignores escapes
// String interpolation (BEST WAY)
string name = "John";
int age = 30;
string message = $"My name is {name} and I'm {age} years old";
// Common String Methods
string text = " Hello World ";
// Length
int length = text.Length; // 15 (including spaces)
// Case conversion
string upper = text.ToUpper(); // " HELLO WORLD "
string lower = text.ToLower(); // " hello world "
// Trimming
string trimmed = text.Trim(); // "Hello World"
string trimmedStart = text.TrimStart(); // "Hello World "
string trimmedEnd = text.TrimEnd(); // " Hello World"
// Searching
bool contains = text.Contains("World"); // true
int indexOf = text.IndexOf("World"); // 7 (position)
int lastIndexOf = text.LastIndexOf("o"); // 9
bool startsWith = text.StartsWith(" He"); // true
bool endsWith = text.EndsWith("ld "); // true
// Substrings
string world = text.Substring(7, 5); // "World" (start, length)
string fromIndex = text.Substring(7); // "World " (start to end)
// Replacement
string replaced = text.Replace("World", "C#"); // " Hello C# "
// Splitting and joining
string csv = "apple,banana,orange";
string[] fruits = csv.Split(','); // ["apple", "banana", "orange"]
string joined = string.Join(" | ", fruits); // "apple | banana | orange"
// Checking for null/empty
bool isEmpty = string.IsNullOrEmpty(text); // false
bool isWhiteSpace = string.IsNullOrWhiteSpace(text); // false
// Formatting
string formatted = string.Format("{0} is {1}", name, age);
string money = string.Format("{0:C}", 19.99); // "$19.99"
string percentage = string.Format("{0:P}", 0.75); // "75.00%"
// StringBuilder (for many concatenations)
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("Hello");
sb.Append(" ");
sb.Append("World");
string result = sb.ToString(); // "Hello World"
8. Arrays
// SINGLE-DIMENSIONAL ARRAYS
// Declaration and initialization
int[] numbers = new int[5]; // Array of 5 integers (default 0)
numbers[0] = 10; // Set first element
numbers[1] = 20; // Set second element
int first = numbers[0]; // Get first element
// Different ways to create arrays
int[] nums1 = new int[] { 1, 2, 3, 4, 5 };
int[] nums2 = new int[5] { 1, 2, 3, 4, 5 };
int[] nums3 = { 1, 2, 3, 4, 5 }; // Simplest syntax
// Array properties and methods
int[] arr = { 5, 2, 8, 1, 9 };
int length = arr.Length; // 5
Array.Sort(arr); // { 1, 2, 5, 8, 9 }
Array.Reverse(arr); // { 9, 8, 5, 2, 1 }
int index = Array.IndexOf(arr, 5); // 2 (position of 5)
Array.Clear(arr, 0, 2); // { 0, 0, 5, 2, 1 }
// Loop through arrays
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
foreach (int num in arr)
{
Console.WriteLine(num);
}
// MULTI-DIMENSIONAL ARRAYS (Rectangular)
int[,] matrix = new int[3, 4]; // 3 rows, 4 columns
matrix[0, 0] = 1; // First row, first column
matrix[1, 2] = 5; // Second row, third column
// Initialize multi-dimensional
int[,] grid = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
// Get dimensions
int rows = grid.GetLength(0); // 3
int cols = grid.GetLength(1); // 3
// Loop through 2D array
for (int i = 0; i < grid.GetLength(0); i++)
{
for (int j = 0; j < grid.GetLength(1); j++)
{
Console.Write($"{grid[i, j]} ");
}
Console.WriteLine();
}
// JAGGED ARRAYS (Array of arrays)
int[][] jagged = new int[3][]; // Array of 3 arrays
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5 };
jagged[2] = new int[] { 6, 7, 8, 9 };
// Access jagged array
int value = jagged[1][2]; // 5 (second array, third element)
// Loop through jagged array
for (int i = 0; i < jagged.Length; i++)
{
for (int j = 0; j < jagged[i].Length; j++)
{
Console.Write($"{jagged[i][j]} ");
}
Console.WriteLine();
}
// ARRAY METHODS
int[] source = { 1, 2, 3, 4, 5 };
int[] destination = new int[3];
Array.Copy(source, destination, 3); // destination = { 1, 2, 3 }
Array.ConstrainedCopy(source, 0, destination, 0, 3); // Safe copy
Array.Resize(ref source, 10); // Extends array to 10 elements
9. Control Flow (if, else, switch)
// IF STATEMENT
int age = 18;
if (age >= 18)
{
Console.WriteLine("You are an adult");
}
// IF-ELSE
if (age >= 18)
{
Console.WriteLine("Adult");
}
else
{
Console.WriteLine("Minor");
}
// IF-ELSE IF
int score = 85;
if (score >= 90)
{
Console.WriteLine("A");
}
else if (score >= 80)
{
Console.WriteLine("B");
}
else if (score >= 70)
{
Console.WriteLine("C");
}
else if (score >= 60)
{
Console.WriteLine("D");
}
else
{
Console.WriteLine("F");
}
// Nested if
bool hasLicense = true;
if (age >= 18)
{
if (hasLicense)
{
Console.WriteLine("You can drive");
}
else
{
Console.WriteLine("You need a license");
}
}
// SWITCH STATEMENT (Traditional)
int day = 3;
string dayName;
switch (day)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
default:
dayName = "Weekend";
break;
}
// SWITCH WITH MULTIPLE CASES
int month = 4;
string season;
switch (month)
{
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
default:
season = "Fall";
break;
}
// SWITCH EXPRESSION (C# 8+ - Modern way)
string result = day switch
{
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
_ => "Weekend" // _ is default pattern
};
// More complex switch expression
string grade = score switch
{
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
>= 60 => "D",
_ => "F"
};
// CONDITIONAL (TERNARY) OPERATOR - shorthand if-else
string status = age >= 18 ? "Adult" : "Minor";
// Nested ternary (use sparingly - hurts readability)
string result2 = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";
10. Loops (for, while, do-while, foreach)
// FOR LOOP - When you know how many times
// Syntax: for(initialization; condition; increment/decrement)
// Count from 1 to 10
for (int i = 1; i <= 10; i++)
{
Console.WriteLine(i);
}
// Count backwards
for (int i = 10; i >= 1; i--)
{
Console.WriteLine(i);
}
// Step by 2
for (int i = 0; i <= 20; i += 2)
{
Console.WriteLine(i); // 0, 2, 4, 6...
}
// Multiple variables
for (int i = 0, j = 10; i < j; i++, j--)
{
Console.WriteLine($"i={i}, j={j}");
}
// Nested loops - multiplication table
for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= 10; j++)
{
Console.Write($"{i * j,4}"); // 4 = width for alignment
}
Console.WriteLine();
}
// WHILE LOOP - Check condition first, may not execute
int count = 1;
while (count <= 5)
{
Console.WriteLine(count);
count++;
}
// While with user input
string input = "";
while (input != "quit")
{
Console.Write("Enter command (quit to exit): ");
input = Console.ReadLine();
Console.WriteLine($"You entered: {input}");
}
// DO-WHILE LOOP - Executes at least once
int number;
do
{
Console.Write("Enter a positive number: ");
number = int.Parse(Console.ReadLine());
} while (number <= 0);
// FOREACH LOOP - For collections/arrays
string[] names = { "Alice", "Bob", "Charlie", "David" };
foreach (string name in names)
{
Console.WriteLine($"Hello, {name}");
}
// foreach with var
foreach (var item in names)
{
Console.WriteLine(item);
}
// foreach with array modification - can't modify collection!
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
// numbers[num] = num * 2; // ERROR! Can't modify in foreach
Console.WriteLine(num);
}
// Use for loop to modify
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = numbers[i] * 2; // OK
}
// LOOP CONTROL STATEMENTS
// break - exit loop immediately
for (int i = 1; i <= 10; i++)
{
if (i == 5)
break; // Stops at 5
Console.WriteLine(i); // 1,2,3,4
}
// continue - skip to next iteration
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
continue; // Skip even numbers
Console.WriteLine(i); // 1,3,5,7,9
}
// goto (rarely used, but exists)
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (i * j == 42)
goto found; // Break out of both loops
}
}
found:
Console.WriteLine("Found the number!");
// INFINITE LOOPS - Be careful!
// while (true) { } // Will run forever
// for(;;) { } // Also infinite
// PRACTICAL EXAMPLES
// Sum of numbers 1 to 100
int sum = 0;
for (int i = 1; i <= 100; i++)
{
sum += i;
}
Console.WriteLine($"Sum: {sum}"); // 5050
// Find factorial
int factorial = 1;
int n = 5;
for (int i = 1; i <= n; i++)
{
factorial *= i;
}
Console.WriteLine($"{n}! = {factorial}"); // 120
// Prime number check
int numToCheck = 17;
bool isPrime = true;
if (numToCheck < 2)
isPrime = false;
else
{
for (int i = 2; i <= Math.Sqrt(numToCheck); i++)
{
if (numToCheck % i == 0)
{
isPrime = false;
break;
}
}
}
Console.WriteLine($"{numToCheck} is prime: {isPrime}");
QUICK REFERENCE CARD
Common Patterns
// Input validation loop
int number;
do {
Console.Write("Enter number between 1-10: ");
} while (!int.TryParse(Console.ReadLine(), out number) || number < 1 || number > 10);
// Process array
int[] data = { 1, 2, 3, 4, 5 };
for (int i = 0; i < data.Length; i++)
{
// Process each element
}
// String comparison (case-insensitive)
if (string.Equals(input, "yes", StringComparison.OrdinalIgnoreCase))
// Safe parsing
if (int.TryParse(userInput, out int result))
{
// Use result
}
// Null checking
if (someString != null && someString.Length > 0)
// or
if (!string.IsNullOrEmpty(someString))
Practice Exercises for Module 0
Exercise 1: Temperature Converter
// Write a program that:
// 1. Asks user for temperature in Celsius
// 2. Converts to Fahrenheit (C * 9/5 + 32)
// 3. Displays the result
// 4. Also displays Kelvin (C + 273.15)
// Solution:
Console.Write("Enter temperature in Celsius: ");
double celsius = double.Parse(Console.ReadLine());
double fahrenheit = celsius * 9 / 5 + 32;
double kelvin = celsius + 273.15;
Console.WriteLine($"{celsius}°C = {fahrenheit}°F = {kelvin}K");
Exercise 2: Number Guessing Game
// Write a program that:
// 1. Generates random number between 1-100
// 2. Lets user guess until correct
// 3. Gives "Too high" or "Too low" hints
// 4. Tracks number of guesses
// Solution:
Random random = new Random();
int secretNumber = random.Next(1, 101);
int guess = 0;
int attempts = 0;
Console.WriteLine("Guess the number between 1-100!");
while (guess != secretNumber)
{
Console.Write("Enter your guess: ");
guess = int.Parse(Console.ReadLine());
attempts++;
if (guess < secretNumber)
Console.WriteLine("Too low!");
else if (guess > secretNumber)
Console.WriteLine("Too high!");
else
Console.WriteLine($"Correct! You took {attempts} attempts.");
}
Exercise 3: Grade Calculator
// Write a program that:
// 1. Asks for 5 test scores
// 2. Stores them in an array
// 3. Calculates average
// 4. Assigns letter grade (90+ = A, 80+ = B, etc.)
// 5. Displays all scores, average, and grade
// Solution:
int[] scores = new int[5];
int sum = 0;
for (int i = 0; i < scores.Length; i++)
{
Console.Write($"Enter score {i + 1}: ");
scores[i] = int.Parse(Console.ReadLine());
sum += scores[i];
}
double average = sum / (double)scores.Length;
string letterGrade;
if (average >= 90) letterGrade = "A";
else if (average >= 80) letterGrade = "B";
else if (average >= 70) letterGrade = "C";
else if (average >= 60) letterGrade = "D";
else letterGrade = "F";
Console.WriteLine("\nScores: " + string.Join(", ", scores));
Console.WriteLine($"Average: {average:F2}");
Console.WriteLine($"Grade: {letterGrade}");
Module 0 Summary Checklist
✅ Understand what C# and .NET are
✅ Write Hello World program
✅ Declare and use variables (int, string, bool, double, decimal)
✅ Get input from user with Console.ReadLine()
✅ Display output with Console.WriteLine()
✅ Use all operators (arithmetic, comparison, logical)
✅ Work with strings and use common string methods
✅ Create and manipulate arrays (single, multi, jagged)
✅ Use if/else and switch for decision making
✅ Use all loop types (for, while, do-while, foreach)