Back To Home
Code Newb

Learn C#!

Lesson 1: Introduction to C#

1.1 What is C#?

C# (pronounced "C Sharp") is a modern, object-oriented programming language developed by Microsoft. It is widely used for building Windows applications, web applications, and games using Unity.

1.2 Why Learn C#?

  • Versatile: Used in desktop, web, mobile, and game development.
  • Strongly Typed: Helps catch errors at compile time.
  • Object-Oriented: Encourages clean and modular code.
  • Large Community: Extensive documentation and support.

Create Your First C# Program

Open a terminal and run:

dotnet new console -o MyFirstApp
cd MyFirstApp
dotnet run

This will create a simple "Hello, World!" program.

1.4 Understanding Variables and Data Types

Variables: A variable stores a value that can change.

string name = "Alice";
int age = 25;
Console.WriteLine(name + " is " + age + " years old.");

Data Types:

  • int: Whole numbers (e.g., 10, -5).
  • float: Decimal numbers (e.g., 3.14f).
  • double: Larger decimal numbers (e.g., 3.14).
  • string: Text (e.g., "Hello").
  • bool: true or false.

1.5 Basic Operations

C# supports basic mathematical operations:

int x = 10;
int y = 5;
Console.WriteLine(x + y);  // Addition
Console.WriteLine(x - y);  // Subtraction
Console.WriteLine(x * y);  // Multiplication
Console.WriteLine(x / y);  // Division

1.6 Coding Challenge: Simple Math Calculator

Task: Write a C# program that asks the user for two numbers and prints their sum, difference, product, and quotient.

Example Output:

Enter first number: 8
Enter second number: 2
Sum: 10
Difference: 6
Product: 16
Quotient: 4.0

Lesson 2: Control Flow in C#

2.1 Conditional Statements (if, else, switch)

C# provides if-else and switch statements for decision-making.

int age = 20;
if (age < 18) {
    Console.WriteLine("You are a minor.");
} else if (age == 18) {
    Console.WriteLine("You just became an adult!");
} else {
    Console.WriteLine("You are an adult.");
}

2.2 Loops (for, while, do-while)

Loops allow you to repeat a block of code.

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

// While loop
int x = 0;
while (x < 5) {
    Console.WriteLine("Value of x: " + x);
    x++;
}

2.3 Loop Control Statements (break, continue)

break: Exits the loop.

continue: Skips the current iteration.

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;  // Exit the loop
    }
    if (i % 2 == 0) {
        continue;  // Skip even numbers
    }
    Console.WriteLine(i);
}

2.4 Coding Challenge: FizzBuzz

Write a program that prints numbers from 1 to 20 but:

  • Prints "Fizz" for multiples of 3.
  • Prints "Buzz" for multiples of 5.
  • Prints "FizzBuzz" for multiples of both 3 and 5.

2.4 Coding Challenge: FizzBuzz

Write a program that prints numbers from 1 to 20 but:

Lesson 3: Functions and Methods in C#

3.1 Defining Methods

Methods help break down a large program into smaller, manageable parts.

void Greet(string name) {
    Console.WriteLine("Hello, " + name + "!");
}

Greet("Alice");  // Output: Hello, Alice!

3.2 Parameters and Return Values

Methods can take parameters and return values.

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

int result = Add(5, 10);
Console.WriteLine(result);  // Output: 15

3.3 Method Overloading

You can define multiple methods with the same name but different parameters.

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

double Add(double a, double b) {
    return a + b;
}

3.4 Coding Challenge: Even or Odd Checker

Write a method that:

Lesson 4: Object-Oriented Programming in C#

4.1 Classes and Objects

A class is a blueprint for creating objects.

class Car {
    public string Brand { get; set; }
    public string Model { get; set; }

    public void DisplayInfo() {
        Console.WriteLine(Brand + " " + Model);
    }
}

Car myCar = new Car();
myCar.Brand = "Toyota";
myCar.Model = "Camry";
myCar.DisplayInfo();  // Output: Toyota Camry

4.2 Encapsulation

Encapsulation restricts direct access to data.

class BankAccount {
    private double balance;

    public void Deposit(double amount) {
        balance += amount;
    }

    public double GetBalance() {
        return balance;
    }
}

4.3 Inheritance

Inheritance allows a class to inherit properties and methods from another class.

class Vehicle {
    public string Brand { get; set; }

    public void Start() {
        Console.WriteLine(Brand + " is starting...");
    }
}

class Car : Vehicle {
    public void Honk() {
        Console.WriteLine("Beep beep!");
    }
}

4.4 Polymorphism

Polymorphism allows methods to have the same name but different implementations.

class Animal {
    public virtual void Speak() {
        Console.WriteLine("Animal makes a sound");
    }
}

class Dog : Animal {
    public override void Speak() {
        Console.WriteLine("Woof!");
    }
}

4.5 Coding Challenge: Employee Management System

Create a class-based program that:

Lesson 5: Exception Handling in C#

5.1 Understanding Exceptions

Exceptions are runtime errors that can be handled.

try {
    int x = 10 / 0;
} catch (DivideByZeroException e) {
    Console.WriteLine("Cannot divide by zero!");
}

5.2 Handling Multiple Exceptions

You can handle multiple exceptions using multiple catch blocks.

try {
    int[] numbers = { 1, 2, 3 };
    Console.WriteLine(numbers[5]);
} catch (IndexOutOfRangeException e) {
    Console.WriteLine("Index out of range!");
} catch (Exception e) {
    Console.WriteLine("An error occurred!");
}

5.3 Finally Block

The finally block always executes, whether an exception occurs or not.

try {
    // Code that may throw an exception
} catch (Exception e) {
    Console.WriteLine("Error: " + e.Message);
} finally {
    Console.WriteLine("Cleanup code here.");
}

5.4 Custom Exceptions

You can create custom exceptions by inheriting from Exception.

class AgeException : Exception {
    public AgeException(string message) : base(message) {}
}

void CheckAge(int age) {
    if (age < 18) {
        throw new AgeException("You must be 18 or older!");
    }
}

5.5. Coding Challenge: Safe Division

Write a method that:

Lesson 6: File Handling in C#

6.1 Reading and Writing Files

C# provides the System.IO namespace for file handling.

// Writing to a file
File.WriteAllText("example.txt", "Hello, World!");

// Reading from a file
string content = File.ReadAllText("example.txt");
Console.WriteLine(content);  // Output: Hello, World!

6.2 Working with Directories

You can create, delete, and list directories.

// Create a directory
Directory.CreateDirectory("MyFolder");

// List files in a directory
string[] files = Directory.GetFiles("MyFolder");
foreach (string file in files) {
    Console.WriteLine(file);
}

6.3 Coding Challenge: Word Counter

Write a program that:

Lesson 7: Advanced C# Concepts

7.1 LINQ (Language Integrated Query)

LINQ allows you to query collections in a SQL-like manner.

int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = from num in numbers
                  where num % 2 == 0
                  select num;

foreach (int num in evenNumbers) {
    Console.WriteLine(num);
}

7.2 Delegates and Events

Delegates are type-safe function pointers, and events are based on delegates.

public delegate void MyDelegate(string message);

public class MyClass {
    public event MyDelegate MyEvent;

    public void TriggerEvent() {
        MyEvent?.Invoke("Event triggered!");
    }
}

7.3 Asynchronous Programming

Asynchronous programming allows you to run tasks concurrently.

async Task FetchDataAsync() {
    await Task.Delay(1000);  // Simulate a delay
    return "Data fetched!";
}

async Task Main() {
    string result = await FetchDataAsync();
    Console.WriteLine(result);
}

7.4 Coding Challenge: LINQ Query

Write a LINQ query that:

Lesson 8: C# and Databases

8.1 Connecting to a Database

C# can connect to databases using ADO.NET or Entity Framework.

using (var connection = new SqlConnection("YourConnectionString")) {
    connection.Open();
    var command = new SqlCommand("SELECT * FROM Users", connection);
    var reader = command.ExecuteReader();
    while (reader.Read()) {
        Console.WriteLine(reader["Username"]);
    }
}

8.2 Entity Framework

Entity Framework is an ORM (Object-Relational Mapping) tool for C#.

public class User {
    public int Id { get; set; }
    public string Username { get; set; }
}

public class MyDbContext : DbContext {
    public DbSet Users { get; set; }
}

using (var context = new MyDbContext()) {
    var users = context.Users.ToList();
    foreach (var user in users) {
        Console.WriteLine(user.Username);
    }
}

8.3 Coding Challenge : Database Query

Write a program that:

Lesson 9: C# and Web Development

9.1 ASP.NET Core

ASP.NET Core is a framework for building web applications in C#.

public class Startup {
    public void ConfigureServices(IServiceCollection services) {
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app) {
        app.UseRouting();
        app.UseEndpoints(endpoints => {
            endpoints.MapControllers();
        });
    }
}

9.2 Building a REST API

You can build RESTful APIs using ASP.NET Core.

[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase {
    [HttpGet]
    public IActionResult GetUsers() {
        return Ok(new[] { "Alice", "Bob" });
    }
}

9.3 Coding Challenge: Simple Web API

Create a simple REST API that:

Lesson 10: Final Project

10.1 Project Overview

Build a complete C# application that incorporates all the concepts learned so far.

10.2 Project Ideas

  • Inventory Management System: Manage products, categories, and orders.
  • Task Manager: Create, update, and delete tasks.
  • E-commerce Platform: Manage products, orders, and customers.

Final Project: Build a Complete Application

Use all the concepts you've learned to build a fully functional C# application.