C#: From Zero to Practical
A concise course covering C# fundamentals to intermediate topics, with examples and exercises.
Author: Generated by ChatGPT
Contents
1. Course Overview & Setup
2. Basics: Types, Variables, and Operators
3. Control Flow & Methods
4. Object-Oriented Programming (Classes & Objects)
5. Inheritance, Polymorphism & Interfaces
6. Collections & Generics
7. Exceptions & Error Handling
8. LINQ & Functional Style
9. Asynchronous Programming: async/await
10. File I/O & Serialization
11. Networking & HTTP
12. Project: Simple To-Do App (Console or WinForms/WPF)
Appendix: Cheatsheet & Answers
1. Course Overview & Setup
What you'll learn: C# syntax, OOP, LINQ, async/await, and a small project. Tools: .NET SDK, Visual
Studio or VS Code with C# extension.
Exercises:
- Install .NET SDK and run `dotnet new console -o HelloWorld`. Build and run.
2. Basics: Types, Variables, and Operators
C# is statically typed. Value types: int, double, bool, char, struct. Reference types: classes, arrays,
interfaces. Nullable types and type inference with `var`.
// Hello world and variables
using System;
class Program {
static void Main() {
string name = "Ada";
int age = 30;
Console.WriteLine($"Hello {name}, age {age}");
}
}
Exercises:
- Declare variables of each primitive type and print them.
3. Control Flow & Methods
Conditionals (if/else, switch), loops (for, while, foreach). Methods (static vs instance), overloading, optional
and named parameters.
// Method example
static int Add(int a, int b) {
return a + b;
}
for (int i = 0; i < 5; i++) {
Console.WriteLine(i);
}
Exercises:
- Write a method to compute factorial iteratively and recursively.
4. Object-Oriented Programming (Classes & Objects)
Classes encapsulate state and behavior. Constructors, fields, properties, methods, access modifiers
(private/protected/public).
// Simple class
public class User {
public string Name { get; set; }
public int Age { get; set; }
public User(string name, int age) {
Name = name;
Age = age;
}
}
Exercises:
- Create a `Book` class with title, author, and method to display info.
5. Inheritance, Polymorphism & Interfaces
Use `:` for inheritance. Override methods with `override`. Interfaces define contracts. Abstract classes
combine partial implementation with abstraction.
// Inheritance example
public class Animal {
public virtual void Speak() { Console.WriteLine("..."); }
}
public class Dog : Animal {
public override void Speak() { Console.WriteLine("Woof"); }
}
Exercises:
- Design an interface `IDrawable` and implement it in two classes.
6. Collections & Generics
Use List, Dictionary, HashSet. Learn generics and type safety. Iteration with foreach.
// Collections example
var names = new List<string> {"Sam", "Lee"};
foreach (var n in names) Console.WriteLine(n);
Exercises:
- Given a list of integers, return a dictionary of value -> frequency.
7. Exceptions & Error Handling
Exceptions are handled with try/catch/finally. Create custom exceptions. Always handle expected errors
gracefully.
try {
var text = File.ReadAllText("data.txt");
} catch (IOException e) {
Console.WriteLine(e.Message);
}
Exercises:
- Create a custom exception and throw it when invalid input is given.
8. LINQ & Functional Style
LINQ (Language Integrated Query) allows filtering, mapping, aggregation. Supports query syntax and
method syntax.
// LINQ example
var nums = new List<int> {1,2,3,4,5};
var evens = nums.Where(n => n % 2 == 0).Select(n => n * n).ToList();
Exercises:
- Use LINQ to compute average of a list of numbers.
9. Asynchronous Programming: async/await
Async/await simplifies asynchronous programming. Tasks represent operations. Use Task, Task, and
async methods.
// Async example
async Task Demo() {
await Task.Delay(500);
Console.WriteLine("Half second later");
}
Exercises:
- Write an async method to fetch data from a web API using HttpClient.
10. File I/O & Serialization
Use System.IO for file handling. Use JSON serialization with System.Text.Json or Newtonsoft.Json.
// File write/read
File.WriteAllText("notes.txt", "Hello");
var text = File.ReadAllText("notes.txt");
Exercises:
- Read a CSV file and parse records into objects.
11. Networking & HTTP
Use HttpClient to make HTTP requests. Deserialize JSON responses.
using var client = new HttpClient();
var res = await client.GetStringAsync("https://api.example.com");
Console.WriteLine(res);
Exercises:
- Call a public REST API and print a field from JSON response.
12. Project: Simple To-Do App (Console or WPF)
Outline: Create a console or WPF app that allows adding, listing, completing, and removing tasks. Persist
tasks to a JSON file.
// Task model
public class TaskItem {
public string Text { get; set; }
public bool Done { get; set; }
public TaskItem(string text) { Text = text; Done = false; }
public void Complete() { Done = true; }
public override string ToString() => (Done ? "[x] " : "[ ] ") + Text;
}
Project Steps:
- Create TaskItem class and TaskManager to hold a List.
- Implement console menu: add, list, complete, delete, save, load.
- Persist tasks to a JSON file using System.Text.Json.
- (Optional) Create a WPF GUI with buttons and list binding.
Appendix: C# Cheatsheet
Declaration int n = 5; string s = "hi"; var x = 42;
Class public class X { private int v; public X(int v){this.v=v;} }
Collections List<T>, Dictionary<TKey,TValue>, HashSet<T>
LINQ nums.Where(n=>n%2==0).Select(n=>n*n)
Async async Task Foo(){ await Task.Delay(1000);}
Answers (selected)
Factorial (recursive) example:
static int Factorial(int n) {
if (n <= 1) return 1;
return n * Factorial(n - 1);
}
LINQ average example:
double avg = nums.Average();