Overview
Learn C# by reading code. This by-example tutorial teaches C# through 85 heavily annotated, self-contained code examples achieving 95% language coverage. If you're an experienced programmer who prefers learning by reading working code rather than narrative explanations, this is your path.
What is By Example?
By Example is a code-first learning approach designed for experienced developers switching to C# from other languages. Instead of lengthy explanations followed by code snippets, you'll see complete, runnable programs with inline annotations explaining what each line does and why it matters.
Target audience: Seasonal programmers, software engineers, and developers with experience in Python, Java, JavaScript, or other languages who want to learn C# efficiently.
How This Tutorial Works
Structure
- Beginner (Examples 1-30): Fundamentals and core syntax - 0-40% coverage
- Intermediate (Examples 31-60): Production patterns and framework features - 40-75% coverage
- Advanced (Examples 61-85): Expert mastery and optimization - 75-95% coverage
Example Format
Each example follows a five-part structure:
- Brief explanation (2-3 sentences) - What is this concept and why does it matter?
- Diagram (when appropriate) - Visual representation of flow, state, or architecture
- Heavily annotated code - Complete, runnable program with inline
// =>annotations - Key takeaway (1-2 sentences) - The essential insight distilled
- Why it matters (50-100 words) - Production relevance and real-world impact
Example: Annotation Style
var numbers = new List<int> { 1, 2, 3, 4, 5 }; // => numbers is List<int> with 5 elements
// => List is mutable, dynamic-sized collection
var doubled = numbers.Select(n => n * 2); // => LINQ Select transforms each element
// => Returns IEnumerable<int> (lazy evaluation)
// => Does NOT execute yet (deferred execution)
var result = doubled.ToList(); // => Forces evaluation, creates new List<int>
// => result is [2, 4, 6, 8, 10]
// => numbers unchanged: [1, 2, 3, 4, 5]What You'll Learn
Coverage: 95% of C# for Production Work
Included:
- Core syntax and semantics (types, variables, control flow)
- Object-oriented programming (classes, interfaces, inheritance)
- Modern C# features (records, pattern matching, nullable reference types)
- LINQ (query syntax and method syntax)
- Async/await and Task-based async programming
- Collections and generics
- Delegates, events, and lambda expressions
- File I/O and serialization
- HTTP clients and ASP.NET Core basics
- Entity Framework Core and database access
- Testing with xUnit/NUnit
- Advanced memory techniques (Span
, Memory ) - Performance optimization
- Reflection and source generators
Excluded (the 5% edge cases):
- COM interop and P/Invoke internals
- Rarely-used legacy features (.NET Framework specifics)
- Framework source code implementation details
- Platform-specific advanced features
Self-Contained Examples
Every example is copy-paste-runnable. Each example includes:
- Complete using statements
- All necessary class definitions
- Helper methods defined inline
- No references to previous examples (you can start anywhere)
Example independence: You can jump to Example 42, copy the code, run it, and understand the concept without reading Examples 1-41.
Why Code-First?
Traditional tutorials explain concepts, then show code. By Example inverts this:
- See the code first - Complete, working program
- Run it immediately - Verify it works on your machine
- Read annotations - Understand what each line does
- Absorb the pattern - Internalize through direct interaction
Benefits:
- Faster learning - No walls of text before seeing actual code
- Immediate verification - Run code to confirm your understanding
- Reference-friendly - Come back later to find specific patterns
- Production-focused - Examples use real-world patterns, not toy code
How to Use This Tutorial
If You're New to Programming
Start with Quick Start first, then return to By Example for comprehensive coverage.
If You Know Another Language
Jump straight into Beginner examples. You'll recognize patterns from other languages but see C#-specific syntax and idioms.
If You Know Some C
Start with Intermediate or Advanced based on your comfort level. Each example is self-contained, so you won't get lost.
As a Reference
Use the example index to find specific topics (e.g., "How do I use async/await?" → Example 47).
Comparison to Narrative Tutorials
| Aspect | By Example (This Tutorial) | Narrative Tutorial |
|---|---|---|
| Approach | Code-first (show, then explain) | Explanation-first (tell, then show) |
| Target Audience | Experienced developers | Beginners and intermediate |
| Coverage | 95% (comprehensive) | 60-85% (focused depth) |
| Example Count | 85 examples | 15-30 examples |
| Learning Style | Read code, run code, understand | Read explanation, see code |
| Use as Reference | Excellent (self-contained examples) | Moderate (sequential narrative) |
Both are valid approaches. Choose based on your learning style and experience level.
Diagrams and Visualizations
Approximately 40% of examples include Mermaid diagrams visualizing:
- Data flow through LINQ pipelines
- Async/await execution flow
- Memory layout (value types vs reference types)
- Inheritance hierarchies
- Request/response cycles in ASP.NET Core
- State machines and pattern matching
All diagrams use a color-blind friendly palette (Blue, Orange, Teal, Purple, Brown) meeting WCAG AA accessibility standards.
Prerequisites
- Programming experience - Familiarity with at least one programming language (Python, Java, JavaScript, etc.)
- C# environment set up - .NET SDK installed and verified (see Initial Setup)
- Code editor ready - VS Code with C# Dev Kit or Visual Studio
- Basic terminal skills - Comfort running
dotnet buildanddotnet run
No prior C# knowledge required - Examples start from fundamentals.
Learning Path
%% Color Palette: Blue #0173B2, Orange #DE8F05, Teal #029E73, Purple #CC78BC, Brown #CA9161
graph TD
A["Initial Setup<br/>0-5%"]
B["Quick Start<br/>5-30%"]
C["By Example: Beginner<br/>0-40%<br/>Examples 1-30"]
D["By Example: Intermediate<br/>40-75%<br/>Examples 31-60"]
E["By Example: Advanced<br/>75-95%<br/>Examples 61-85"]
A --> B
B --> C
C --> D
D --> E
style A fill:#0173B2,stroke:#000,color:#fff
style B fill:#DE8F05,stroke:#000,color:#fff
style C fill:#029E73,stroke:#000,color:#fff
style D fill:#CC78BC,stroke:#000,color:#fff
style E fill:#CA9161,stroke:#000,color:#fff
What's Next?
Ready to start learning? Choose your entry point:
- New to C#? → Beginner Examples (1-30)
- Know the basics? → Intermediate Examples (31-60)
- Experienced with C#? → Advanced Examples (61-85)
Expected Time Investment
Not measured in hours - everyone learns at different speeds. Instead, we measure in coverage depth:
- Beginner: 0-40% coverage through 30 examples
- Intermediate: 40-75% coverage through 30 examples
- Advanced: 75-95% coverage through 25 examples
Work at your own pace. Some developers complete all 85 examples in a weekend; others spread it across weeks while building projects.
Key Principles
- Every example is runnable - Copy, paste, run, verify
- Annotations explain WHY, not just WHAT - Understand the reasoning
- Self-contained is non-negotiable - No hunting for code in other examples
- Production patterns, not toys - Real-world code you'll actually write
- Modern C# features - C# 12, .NET 8, contemporary idioms
Feedback and Improvements
Found an error? See a better way to explain something? Examples are continuously improved based on learner feedback.
Let's start coding! Choose your level and dive into the examples.
Examples by Level
Beginner (Examples 1–30)
- Example 1: Hello World and C# Compilation
- Example 2: Variables with Type Inference (var)
- Example 3: Explicit Type Declarations
- Example 4: Nullable Reference Types
- Example 5: Control Flow - If Statements
- Example 6: Switch Expressions (C# 8.0+)
- Example 7: Loops - For Loop
- Example 8: Loops - Foreach Loop
- Example 9: Methods - Basic Syntax
- Example 10: Lambda Expressions
- Example 11: Classes and Objects
- Example 12: Properties with Get/Set
- Example 13: Auto-Implemented Properties
- Example 14: Constructors
- Example 15: Collections - List
- Example 16: Collections - Dictionary<TKey, TValue>
- Example 17: Collections - HashSet
- Example 18: LINQ - Where (Filtering)
- Example 19: LINQ - Select (Mapping)
- Example 20: LINQ - OrderBy/OrderByDescending
- Example 21: Exception Handling - Try-Catch
- Example 22: Exception Handling - Finally
- Example 23: String Methods
- Example 24: String Interpolation
- Example 25: Value Types vs Reference Types
- Example 26: Null Conditional Operator (?.)
- Example 27: Null Coalescing Operator (??)
- Example 28: Collection Expressions (C# 12.0+)
- Example 29: Primary Constructors (C# 12.0+)
- Example 30: Record Types
Intermediate (Examples 31–60)
- Example 31: Interfaces for Polymorphism
- Example 32: Inheritance - Base and Derived Classes
- Example 33: Abstract Classes - Partial Implementations
- Example 34: Async/Await - Basic Asynchronous Operations
- Example 35: Task.WhenAll - Parallel Async Operations
- Example 36: Task.WhenAny - Race Conditions
- Example 37: File I/O - Reading and Writing Files
- Example 38: JSON Serialization with System.Text.Json
- Example 39: HTTP Client - Making API Requests
- Example 40: LINQ GroupBy - Grouping Data
- Example 41: LINQ Join - Combining Collections
- Example 42: LINQ SelectMany - Flattening Collections
- Example 43: Delegates - Function Pointers
- Example 44: Events - Publisher-Subscriber Pattern
- Example 45: Generics - Type Parameters
- Example 46: Generic Constraints - Restricting Type Parameters
- Example 47: Extension Methods - Adding Methods to Existing Types
- Example 48: Indexers - Array-Like Access
- Example 49: Pattern Matching - Type Patterns and Switch Expressions
- Example 50: Records - Immutable Data Types
- Example 51: Init-Only Properties - Object Initializer Immutability
- Example 52: Tuples - Lightweight Data Structures
- Example 53: IEnumerable
and Deferred Execution - Example 54: Dependency Injection - Constructor Injection
- Example 55: Configuration - Reading App Settings
- Example 56: ASP.NET Core - Minimal API
- Example 57: Entity Framework Core - Basic CRUD
- Example 58: Testing with xUnit - Unit Tests
- Example 59: Nullable Reference Types - Null Safety
- Example 60: LINQ Aggregate Operations - Custom Aggregations
Advanced (Examples 61–85)
- Example 61: ValueTask for High-Performance Async
- Example 62: IAsyncEnumerable for Streaming Data
- Example 63: Span<T> for Zero-Copy Memory Access
- Example 64: Memory<T> for Async-Safe Memory Access
- Example 65: stackalloc and ArrayPool for Buffer Management
- Example 66: Reflection Basics - Type Inspection
- Example 67: Custom Attributes and Attribute Reflection
- Example 68: Expression Trees - Code as Data
- Example 69: Source Generators - Compile-Time Code Generation
- Example 70: Advanced Pattern Matching - List Patterns and Type Patterns
- Example 71: Channels for Producer-Consumer Patterns
- Example 72: SemaphoreSlim for Async Concurrency Control
- Example 73: Lock and Monitor for Thread Safety
- Example 74: Unsafe Code and Pointers
- Example 75: P/Invoke - Calling Native Code
- Example 76: BenchmarkDotNet for Performance Measurement
- Example 77: Minimal APIs - Lightweight HTTP Endpoints
- Example 78: Middleware Pipeline - Request Processing
- Example 79: Health Checks - Service Monitoring
- Example 80: OpenTelemetry - Distributed Tracing
- Example 81: Metrics with OpenTelemetry
- Example 82: Custom with Expressions
- Example 83: Discriminated Unions with Records
- Example 84: SemaphoreSlim vs lock Performance
- Example 85: Source Generator Example - Auto-Property Notification
Last updated February 1, 2026