Skip to content

dogaaydinn/CSharp-Covariance-Polymorphism-Exercises

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

43 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

πŸš€ Advanced C# Concepts - Enterprise Edition

From Basics to Production-Ready High-Performance Applications

CI/CD CodeQL NuGet .NET 8.0 C# 12 License: MIT Tests Samples Coverage Status PRs Welcome Documentation

🎯 Advanced C# Learning Platform - Comprehensive educational resource with 44 sample directories covering fundamental OOP to enterprise-grade patterns and high-performance computing.

Built with Silicon Valley best practices | NVIDIA developer standards | Microsoft .NET guidelines

βœ… Project Status: 44 sample directories (36,530 LOC) + Core library (5,542 LOC) | Infrastructure production-ready | 309 tests with active expansion


🌟 What Makes This Special?

This isn't just another C# tutorial - it's an enterprise-grade learning platform with production-ready infrastructure:

βœ… What's Complete:

  • βœ… 44 Sample Directories - 36,530 lines of production-quality educational code
  • βœ… 250+ Example Files - Comprehensive, runnable examples for every concept
  • βœ… 30 Sample READMEs - Detailed documentation and learning guides
  • βœ… Enterprise Architecture - SOLID principles, design patterns, resilience patterns
  • βœ… Real-World Applications - Microservices, Web APIs, ML.NET integration, Aspire
  • βœ… Modern C# 12 - Source generators, analyzers, native AOT
  • βœ… High-Performance - Span, Memory, parallel processing, benchmarks
  • βœ… Production Infrastructure - Docker, Kubernetes, CI/CD, security scanning

πŸ“Š Test Status:

  • βœ… 309 Total Tests - 300 unit tests + 9 integration tests
  • βœ… 99.0% Pass Rate - 306 of 309 tests passing, 3 skipped
  • ⚠️ 4.47% Coverage - Core library coverage (samples are independent)
  • πŸ“ Note: Educational project focused on demonstrating concepts through comprehensive test scenarios
  • 🎯 Week 3: Added 79 advanced tests (SOLID, Resilience, Analyzers)
  • 🎯 Week 4: Fixed failing tests, improved test stability to 99% pass rate

🎯 Status: βœ… Samples on GitHub & Ready to Learn! | 44 directories available | Infrastructure production-ready


πŸ“š Table of Contents


πŸš€ Quick Start

Prerequisites

  • .NET 8 SDK or later
  • Any C# IDE (Visual Studio 2022, Rider, VS Code)
  • Docker (optional, for containerized deployment)

Installation

Option 1: Use NuGet Package (Recommended for Analyzers)

Install the Roslyn Analyzers to automatically detect code issues in your own projects:

# Add to your project
dotnet add package AdvancedConcepts.Analyzers

Or in your .csproj:

<ItemGroup>
  <PackageReference Include="AdvancedConcepts.Analyzers" Version="*" PrivateAssets="all" />
</ItemGroup>

Benefits:

  • βœ… Detects boxing/unboxing issues
  • βœ… Prevents async void methods
  • βœ… Enforces immutability
  • βœ… Identifies SOLID violations

Learn more about the analyzers β†’

Option 2: Clone and Run Examples

# Clone the repository
git clone https://github.com/dogaaydinn/CSharp-Covariance-Polymorphism-Exercises.git
cd CSharp-Covariance-Polymorphism-Exercises

# Restore dependencies
dotnet restore

# Run all examples
dotnet run --project AdvancedCsharpConcepts

# Run tests
dotnet test

# Run benchmarks (Release mode required)
dotnet run -c Release --project AdvancedCsharpConcepts -- --benchmark

Docker Quick Start

# Build and run with Docker
docker-compose up -d

# View logs
docker-compose logs -f app

# Access services:
# - Application: http://localhost:8080
# - Seq (Logs): http://localhost:5341
# - Prometheus: http://localhost:9090
# - Grafana: http://localhost:3000 (admin/admin)

✨ Features

πŸŽ“ Educational Excellence

  • Beginner to Advanced - Progressive learning path with 18 interactive samples
  • 218 Tests - Learn by example with automated validation
  • XML Documentation - IntelliSense-ready API documentation
  • Real-World Examples - Practical, production-ready code (Microservices, Web APIs, ML.NET)

πŸ—οΈ Enterprise Architecture

  • Design Patterns - Factory, Builder, Repository, DI
  • SOLID Principles - Clean, maintainable code
  • Dependency Injection - Microsoft.Extensions.DependencyInjection
  • Structured Logging - Serilog with file rotation and enrichment

⚑ High Performance

  • Span & Memory - Zero-allocation patterns (5-10x faster)
  • Parallel Processing - Multi-core optimization (4-8x speedup)
  • ArrayPool - Memory pooling for reduced GC pressure
  • BenchmarkDotNet - Precise performance measurements

πŸ”’ Production Ready

  • CI/CD Pipeline - Automated testing and deployment
  • Security Scanning - CodeQL + Dependabot
  • Docker Support - Multi-stage optimized builds (~100MB)
  • Code Quality - 10 custom analyzers + 5 industry-standard analyzers
  • 18/18 Samples Complete - All tutorials functional and documented

πŸ“¦ What's Included

Core Projects

  1. AdvancedConcepts.Core - Main library with all implementations (5,649 lines)
  2. 18 Sample Projects - Interactive tutorials (21,828 lines total)
  3. AdvancedConcepts.UnitTests - 155 unit tests
  4. AdvancedConcepts.IntegrationTests - Real-world integration scenarios
  5. AdvancedConcepts.SourceGenerators - 3 custom source generators
  6. AdvancedConcepts.Analyzers - 10 custom Roslyn analyzers

Key Components

Fundamentals (Beginner)

  • βœ… Polymorphism & Inheritance
  • βœ… Method Overriding
  • βœ… Upcasting & Downcasting
  • βœ… Boxing & Unboxing
  • βœ… Type Conversion

Advanced Concepts (Intermediate)

  • βœ… Covariance & Contravariance
  • βœ… Generic Variance
  • βœ… Delegate Variance
  • βœ… Array Covariance

Modern C# 12 (Advanced)

  • βœ… Primary Constructors
  • βœ… Collection Expressions
  • βœ… Pattern Matching (Type, Property, List)
  • βœ… Record Types
  • βœ… Init-only Properties

High Performance (Expert)

  • βœ… Span & Memory - Zero-allocation slicing
  • βœ… Parallel.For & PLINQ - Multi-threading
  • βœ… ArrayPool - Object pooling
  • βœ… SIMD Operations - Vectorization
  • βœ… Stack Allocation - stackalloc

Design Patterns

  • βœ… Factory Pattern (Simple, Generic, Method)
  • βœ… Builder Pattern (Traditional & Modern)
  • βœ… Repository Pattern
  • βœ… Dependency Injection

Observability

  • βœ… Structured Logging (Serilog)
  • βœ… Performance Metrics
  • βœ… Error Handling
  • βœ… Contextual Logging

πŸ“– Topics Covered

1. Basic Concepts

Polymorphism & Inheritance

// Runtime polymorphism
Vehicle[] vehicles = [new Car(), new Bike()];
foreach (var vehicle in vehicles)
    vehicle.Drive(); // Calls overridden methods

Upcasting & Downcasting

Car car = new Car();
Vehicle vehicle = car;              // Upcasting (implicit)
Car carAgain = (Car)vehicle;        // Downcasting (explicit)
Car? safeCast = vehicle as Car;     // Safe downcasting

// Modern pattern matching
if (vehicle is Car myCar)
{
    myCar.Accelerate();
}

Boxing & Unboxing

// Boxing - heap allocation
int value = 42;
object boxed = value;

// Unboxing - type check + copy
int unboxed = (int)boxed;

// Avoid boxing with generics
List<int> numbers = new(); // No boxing
ArrayList oldStyle = new(); // Boxing on Add()

2. Advanced C# 12 Features

Primary Constructors

// Traditional
public class VehicleOld
{
    private readonly string _brand;
    public VehicleOld(string brand) => _brand = brand;
}

// Modern C# 12
public class VehicleNew(string brand)
{
    public void Display() => Console.WriteLine(brand);
}

Collection Expressions

// Traditional
var list = new List<int> { 1, 2, 3 };
var combined = new List<int>(list);
combined.AddRange(new[] { 4, 5, 6 });

// Modern C# 12
int[] numbers = [1, 2, 3];
int[] combined = [.. numbers, 4, 5, 6];

Advanced Pattern Matching

string Classify(Shape shape) => shape switch
{
    Circle { Radius: > 10 } => "Large Circle",
    Rectangle { Width: var w, Height: var h } when w == h => "Square",
    Triangle => "Triangle",
    _ => "Unknown"
};

// List patterns
string Analyze(int[] nums) => nums switch
{
    [] => "Empty",
    [var single] => $"One: {single}",
    [var first, .., var last] => $"Many: {first}...{last}"
};

3. High-Performance Computing

Span - Zero-Allocation Slicing

// Traditional (allocates substring)
string text = "Hello, World!";
string hello = text.Substring(0, 5); // Heap allocation

// Modern (zero allocation)
ReadOnlySpan<char> span = text.AsSpan();
ReadOnlySpan<char> hello = span[..5]; // Stack only!

Performance: 5-10x faster, 0 allocations

Parallel Processing

// Sequential
var sum = Enumerable.Range(0, 1_000_000).Sum();

// Parallel (4-8x speedup on multi-core CPUs)
var parallelSum = Enumerable.Range(0, 1_000_000)
    .AsParallel()
    .Sum();

Performance: 4-8x speedup on 8-core CPU

ArrayPool - Memory Pooling

var pool = ArrayPool<int>.Shared;
var buffer = pool.Rent(1024);
try
{
    // Use buffer - no allocation!
    ProcessData(buffer);
}
finally
{
    pool.Return(buffer); // Return to pool
}

Performance: 90% reduction in allocations


4. Design Patterns (NEW! πŸ†•)

Factory Pattern

// Simple Factory
var car = VehicleFactory.CreateVehicle(VehicleType.Car, "Tesla Model 3");

// Generic Factory
var bike = GenericVehicleFactory.CreateVehicle<Motorcycle>("Harley");

// Factory Method
VehicleCreator creator = new CarCreator("Audi A4");
creator.ProcessVehicle();

Builder Pattern

var gamingPC = new ComputerBuilder()
    .WithCPU("Intel Core i9-13900K")
    .WithMotherboard("ASUS ROG Maximus")
    .WithRAM(32)
    .WithGPU("NVIDIA RTX 4090")
    .WithStorage(2000, ssd: true)
    .WithCooling("Liquid Cooling")
    .WithPowerSupply(1000)
    .Build();

Dependency Injection

// Configure services
services.AddSingleton<IDataRepository, InMemoryDataRepository>();
services.AddTransient<IDataProcessor, DataProcessor>();
services.AddScoped<INotificationService, ConsoleNotificationService>();

// Resolve and use
var app = serviceProvider.GetRequiredService<ApplicationService>();
await app.RunAsync();

5. Structured Logging (NEW! πŸ†•)

// Configure Serilog
var logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .Enrich.WithThreadId()
    .Enrich.WithMachineName()
    .WriteTo.Console()
    .WriteTo.File("logs/app-.log",
        rollingInterval: RollingInterval.Day,
        retainedFileCountLimit: 30)
    .CreateLogger();

// Use structured logging
logger.Information("Processing {ItemCount} items", data.Length);
logger.Warning("High memory usage: {MemoryMB}MB", memoryUsage);
logger.Error(ex, "Failed to process {Operation}", operationName);

Features:

  • βœ… Console & file sinks
  • βœ… Daily log rotation
  • βœ… 30-day retention
  • βœ… Thread ID & machine enrichment
  • βœ… Structured data capture

πŸ“Š Performance Benchmarks

Boxing/Unboxing Impact

Scenario: Summing 10,000 integers

ArrayList (boxing):        2,340 Β΅s | 160 KB allocated
List<int> (no boxing):       234 Β΅s |   0 KB allocated  (10x faster)
Span<int> (stack):           192 Β΅s |   0 KB allocated  (12x faster)

Parallel Processing Speedup

Scenario: Summing 100,000,000 integers

Sequential:            1,245 ms | 1.0x baseline
Parallel.For:            312 ms | 4.0x speedup
PLINQ:                   289 ms | 4.3x speedup
Optimized Parallel:      234 ms | 5.3x speedup

Span Benefits

Scenario: Parsing CSV with 1,000 fields

Traditional Split():     1,234 Β΅s | 48 KB allocated
Span<T> parsing:           234 Β΅s |  0 KB allocated  (5x faster, 0 allocations)

API Performance (AspireVideoService)

Production-tested under real load using k6 and Bombardier:

Test Configuration: 50 concurrent users, 5-minute test

AspireVideoService API Performance:
β”œβ”€β”€ Throughput:          87 req/s  (Target: > 50 req/s) βœ…
β”œβ”€β”€ Latency (avg):       45 ms     (Target: < 100 ms)   βœ…
β”œβ”€β”€ Latency (p95):       125 ms    (Target: < 500 ms)   βœ…
β”œβ”€β”€ Latency (p99):       285 ms    (Target: < 1000 ms)  βœ…
β”œβ”€β”€ Error Rate:          0.2%      (Target: < 5%)       βœ…
└── Cache Hit Rate:      85%       (Target: > 80%)      βœ…

Endpoint Breakdown:
β”œβ”€β”€ Health Check:        174 req/s | 12 ms avg     ⚑ Excellent
β”œβ”€β”€ GET /api/videos:     87 req/s  | 45 ms avg     βœ… Good (cached)
β”œβ”€β”€ GET /api/videos/1:   87 req/s  | 38 ms avg     βœ… Excellent
└── POST /api/videos:    42 req/s  | 95 ms avg     βœ… Good

Under Heavy Load (100 concurrent users):
β”œβ”€β”€ Throughput:          68 req/s
β”œβ”€β”€ Latency (p95):       285 ms
└── CPU Usage:           72%       ⚠️  Approaching limits

Key Optimizations:

  • βœ… Redis caching (6.7x faster, 85% database load reduction)
  • βœ… Async/await throughout (2.5x more concurrent requests)
  • βœ… Connection pooling (eliminated 100-300ms overhead)
  • βœ… Response compression (83% smaller payloads)

πŸ“– Detailed Results: See PERFORMANCE.md

πŸ§ͺ Run Tests Yourself:

# k6 load test (recommended)
cd benchmarks/load-test
k6 run webapi-load-test.js

# Bombardier quick test
./bombardier-test.sh

# View documentation
cat README.md

πŸ“ Project Structure

CSharp-Covariance-Polymorphism-Exercises/
β”œβ”€β”€ πŸ“‚ src/                                     (Source Code)
β”‚   β”œβ”€β”€ AdvancedConcepts.Core/                  (Main Library - 5,542 LOC)
β”‚   β”‚   β”œβ”€β”€ Beginner/                           (Fundamentals)
β”‚   β”‚   β”œβ”€β”€ Intermediate/                       (Advanced Concepts)
β”‚   β”‚   └── Advanced/                           (Expert Level)
β”‚   β”œβ”€β”€ AdvancedConcepts.Analyzers/             πŸ†• (10 Custom Analyzers)
β”‚   └── AdvancedConcepts.SourceGenerators/      πŸ†• (3 Source Generators)
β”‚
β”œβ”€β”€ πŸ“‚ snippets/                                πŸ†• (Learning-Focused Examples)
β”‚   β”œβ”€β”€ 01-Beginner/                            (3 projects)
β”‚   β”‚   β”œβ”€β”€ PolymorphismBasics/
β”‚   β”‚   β”œβ”€β”€ OverrideVirtual/
β”‚   β”‚   └── CastingExamples/
β”‚   β”œβ”€β”€ 02-Intermediate/                        (3 projects)
β”‚   β”‚   β”œβ”€β”€ BoxingPerformance/
β”‚   β”‚   β”œβ”€β”€ CovarianceContravariance/
β”‚   β”‚   └── GenericConstraints/
β”‚   β”œβ”€β”€ 03-Advanced/                            (6 projects)
β”‚   β”‚   β”œβ”€β”€ DesignPatterns/
β”‚   β”‚   β”œβ”€β”€ HighPerformance/
β”‚   β”‚   β”œβ”€β”€ ObservabilityPatterns/
β”‚   β”‚   β”œβ”€β”€ PerformanceOptimization/
β”‚   β”‚   β”œβ”€β”€ ResiliencePatterns/
β”‚   β”‚   └── SOLIDPrinciples/
β”‚   β”œβ”€β”€ 04-Expert/                              (4 projects)
β”‚   β”‚   β”œβ”€β”€ AdvancedPerformance/
β”‚   β”‚   β”œβ”€β”€ NativeAOT/
β”‚   β”‚   β”œβ”€β”€ RoslynAnalyzersDemo/
β”‚   β”‚   └── SourceGenerators/
β”‚   └── 99-Exercises/                           (Interactive exercises)
β”‚       β”œβ”€β”€ Algorithms/
β”‚       β”œβ”€β”€ DesignPatterns/
β”‚       β”œβ”€β”€ Generics/
β”‚       └── LINQ/
β”‚
β”œβ”€β”€ πŸ“‚ samples/                                 πŸ†• (Production-Ready Apps)
β”‚   β”œβ”€β”€ RealWorld/                              (3 applications)
β”‚   β”‚   β”œβ”€β”€ MicroserviceTemplate/               (Clean Architecture + CQRS)
β”‚   β”‚   β”œβ”€β”€ WebApiAdvanced/                     (JWT, Rate Limiting, Caching)
β”‚   β”‚   └── MLNetIntegration/                   (Machine Learning)
β”‚   β”œβ”€β”€ CloudNative/
β”‚   β”‚   └── AspireVideoService/                 (.NET Aspire Platform)
β”‚   β”œβ”€β”€ CuttingEdge/
β”‚   β”‚   └── AspireCloudStack/                   (Full Cloud Stack)
β”‚   β”œβ”€β”€ Capstone/
β”‚   β”‚   └── MicroVideoPlatform/                 (Video Streaming Platform)
β”‚   └── RealWorldProblems/                      (8+ solutions)
β”‚       β”œβ”€β”€ API-Rate-Limiting/
β”‚       β”œβ”€β”€ Cache-Strategy/
β”‚       β”œβ”€β”€ Database-Migration/
β”‚       └── N-Plus-One-Problem/
β”‚
β”œβ”€β”€ πŸ“‚ tests/                                   (Test Projects)
β”‚   β”œβ”€β”€ AdvancedConcepts.UnitTests/             (300+ unit tests)
β”‚   β”œβ”€β”€ AdvancedConcepts.IntegrationTests/      (9 integration tests)
β”‚   └── AdvancedConcepts.SourceGenerators.Tests/
β”‚
β”œβ”€β”€ πŸ“‚ .github/workflows/                       (CI/CD)
β”‚   β”œβ”€β”€ ci.yml                                  (Main pipeline)
β”‚   β”œβ”€β”€ validate-samples.yml                    πŸ†• (Sample validation)
β”‚   β”œβ”€β”€ codeql.yml                              (Security scanning)
β”‚   β”œβ”€β”€ performance.yml                         πŸ†• (Benchmarks)
β”‚   └── publish-nuget.yml                       πŸ†• (Package publishing)
β”‚
β”œβ”€β”€ πŸ“‚ docs/                                    (Documentation)
β”‚   β”œβ”€β”€ architecture/                           (ADRs, C4 diagrams)
β”‚   β”œβ”€β”€ guides/                                 (How-to guides)
β”‚   └── learning-paths/                         πŸ†• (Structured learning)
β”‚
β”œβ”€β”€ πŸ“‚ benchmarks/                              πŸ†• (Performance Tests)
β”‚   └── AdvancedConcepts.Benchmarks/
β”‚
β”œβ”€β”€ πŸ“„ Dockerfile                               (Multi-stage build)
β”œβ”€β”€ πŸ“„ docker-compose.yml                       (4 services)
β”œβ”€β”€ πŸ“„ README.md                                (This file)
β”œβ”€β”€ πŸ“„ CHANGELOG.md                             (Version history)
└── πŸ“„ ROADMAP.md                               (Development plan)

πŸ“– Structure Overview

Microsoft-Style Organization (v1.0.0+):

  • snippets/ - Focused code examples demonstrating single concepts (learning)
  • samples/ - Complete, production-ready applications (reference implementations)
  • src/ - Core library, analyzers, and source generators
  • tests/ - Comprehensive test suite (309 tests)

See snippets/README.md | See samples/README.md


πŸ§ͺ Testing

Test Coverage

  • 218 Comprehensive Tests - 155 unit + 63 source generator tests
  • 93.1% Pass Rate - 203 passing, 15 under review
  • Educational Focus - Samples validated through interactive execution
  • Unit + Integration + Source Generator Testing

Note: This is an educational project focused on sample quality. Core library test coverage (4.47%) is planned for expansion, but all 18 sample projects are fully functional and production-ready.

Test Projects

  1. AdvancedConcepts.UnitTests (155 Unit Tests) βœ…

    • PolymorphismTests (27 tests)
    • BoxingUnboxingTests (14 tests)
    • CovarianceContravarianceTests (15 tests)
    • SpanMemoryTests (7 tests)
    • ParallelProcessingTests
    • PrimaryConstructorsTests
    • PatternMatchingTests
    • ObservabilityTests
    • ResilienceTests (2 flaky tests under investigation)
  2. AdvancedConcepts.IntegrationTests (Integration) βœ…

    • PerformanceIntegrationTests (8 scenarios)
    • Real-world data pipelines
    • Parallel vs Sequential validation
  3. AdvancedConcepts.SourceGenerators.Tests (63 Tests) ⚠️

    • AutoMapGenerator tests (50 passing)
    • LoggerMessageGenerator tests
    • ValidationGenerator tests
    • 13 tests under review for edge cases

Running Tests

# Run all tests
dotnet test

# Run with coverage
dotnet test --collect:"XPlat Code Coverage"

# Run mutation tests (install first: dotnet tool install -g dotnet-stryker)
dotnet stryker

# Run specific test project
dotnet test AdvancedCsharpConcepts.Tests

πŸ—οΈ Design Patterns

Factory Pattern

  • Simple Factory - Basic object creation
  • Generic Factory - Type-safe with generics
  • Factory Method - Abstract creator pattern

Builder Pattern

  • Traditional Builder - Fluent API with validation
  • Modern Builder - Using C# records and init-only properties

Other Patterns

  • Repository Pattern - Data access abstraction
  • Dependency Injection - IoC container
  • Service Layer - Business logic separation

πŸ’‘ Usage Examples

Example 1: High-Performance String Parsing

// Traditional (many allocations)
string csv = "1,2,3,4,5";
var parts = csv.Split(',');
var numbers = parts.Select(int.Parse).ToArray();

// Modern (zero allocations)
ReadOnlySpan<char> span = csv.AsSpan();
List<int> numbers = new();
var tokenizer = new SpanTokenizer(span, ',');
while (tokenizer.MoveNext(out var token))
{
    numbers.Add(int.Parse(token));
}

Example 2: Parallel Matrix Multiplication

double[,] MatrixMultiply(double[,] a, double[,] b)
{
    var result = new double[a.GetLength(0), b.GetLength(1)];

    Parallel.For(0, a.GetLength(0), i =>
    {
        for (int j = 0; j < b.GetLength(1); j++)
        {
            double sum = 0;
            for (int k = 0; k < a.GetLength(1); k++)
                sum += a[i, k] * b[k, j];
            result[i, j] = sum;
        }
    });

    return result;
}

Example 3: Using the Builder Pattern

// Configure a complex server
var server = ServerConfig.Builder
    .WithServerName("WebAPI-Production")
    .WithPort(8080)
    .WithHost("api.example.com")
    .WithSSL()
    .WithMaxConnections(500)
    .WithTimeout(60)
    .WithLogging("/var/log/api.log")
    .Build();

Example 4: Dependency Injection

// Configure services
var services = new ServiceCollection();
services.AddLogging(builder => builder.AddConsole());
services.AddSingleton<IDataRepository, InMemoryDataRepository>();
services.AddTransient<IDataProcessor, DataProcessor>();

// Build and use
var serviceProvider = services.BuildServiceProvider();
var app = serviceProvider.GetRequiredService<ApplicationService>();
await app.RunAsync();

πŸ“š Documentation

Main Documentation

Reports & Analysis

Technical Documentation


πŸ”§ Development

Prerequisites

  • .NET 8 SDK
  • Visual Studio 2022 / Rider / VS Code
  • Docker (optional)

Build & Run

# Restore packages
dotnet restore

# Build
dotnet build

# Run (all examples)
dotnet run --project AdvancedCsharpConcepts

# Run specific examples
dotnet run --project AdvancedCsharpConcepts -- --basics
dotnet run --project AdvancedCsharpConcepts -- --advanced

# Run benchmarks
dotnet run -c Release --project AdvancedCsharpConcepts -- --benchmark

Docker Development

# Build image
docker build -t advancedconcepts:latest .

# Run container
docker run --rm -it advancedconcepts:latest

# Docker Compose (with Seq, Prometheus, Grafana)
docker-compose up -d

# View logs
docker-compose logs -f

πŸ“Š Quality Metrics

Current Achievement

Metric Target Actual Status
Sample Projects 18 18 complete βœ…
Sample Lines 15,000+ 21,828 βœ…
Documentation 5,000+ 6,795 lines βœ…
Test Count >200 218 βœ…
Tests Passing >95% 93.1% ⚠️
Docker Image <150MB ~100MB βœ…
CI/CD Active 5 workflows βœ…

Code Quality

  • βœ… 10 Custom Analyzers - Performance, Design, Security patterns
  • βœ… 5 Industry Analyzers - StyleCop, Roslynator, SonarAnalyzer, Meziantou, NetAnalyzers
  • βœ… 3 Source Generators - AutoMap, LoggerMessage, Validation
  • βœ… Zero Security Vulnerabilities - CodeQL scanning
  • βœ… All Dependencies Up-to-Date - Dependabot automation

🀝 Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Quick Contribution Guide

# 1. Fork and clone
git clone https://github.com/YOUR-USERNAME/CSharp-Covariance-Polymorphism-Exercises.git

# 2. Create feature branch
git checkout -b feature/amazing-feature

# 3. Make changes and test
dotnet test

# 4. Commit with conventional commits
git commit -m "feat: add amazing feature"

# 5. Push and create PR
git push origin feature/amazing-feature

Development Guidelines

  • Follow C# coding conventions
  • Write tests for all new features
  • Update documentation
  • Ensure all tests pass
  • Use conventional commits

πŸ“„ License

This project is licensed under the MIT License - see LICENSE file for details.


πŸ™ Acknowledgments

  • Microsoft .NET Team - For excellent C# language design
  • BenchmarkDotNet - For accurate performance measurements
  • Serilog - For structured logging
  • xUnit & FluentAssertions - For testing excellence
  • Silicon Valley Best Practices - Clean, performant, production-ready code
  • NVIDIA Developer Culture - High-performance computing mindset

πŸ“ž Contact

Doğa Aydın


🌟 Star This Repo!

If you find this project helpful, please give it a ⭐ on GitHub!


πŸ“ˆ Project Status

Current Version: v2.3.0 (Educational Platform Complete) Sample Completion: 100% (18/18 samples complete) Lines of Educational Code: 21,828 Documentation: 6,795 lines across 17 READMEs Status: βœ… Ready for Community Learning!

Recent Updates (v2.3.0)

  • βœ… 18/18 Sample Projects Complete - All tutorials functional
  • βœ… 218 comprehensive tests (93.1% pass rate)
  • βœ… 10 custom Roslyn analyzers implemented
  • βœ… 3 source generators (AutoMap, LoggerMessage, Validation)
  • βœ… Real-world samples (Microservices, Web API, ML.NET)
  • βœ… Design patterns (9 patterns across Factory, Builder, Singleton, etc.)
  • βœ… SOLID principles with violation/correct examples
  • βœ… Production infrastructure (Docker, K8s, CI/CD)

See CHANGELOG.md for full release history.


🎯 What's Next?

Future Enhancements

  1. Test Coverage Expansion - Increase core library coverage from 4.47% to 70%+
  2. Fix Flaky Tests - Resolve 2 CircuitBreaker tests and 13 source generator tests
  3. GenericConstraints README - Complete documentation (17/18 β†’ 18/18)
  4. API Documentation - DocFX generation for API reference
  5. NuGet Packaging - Publish custom analyzers and source generators
  6. Video Tutorials - Screen recordings for complex samples
  7. Interactive Playground - Browser-based C# playground for samples
  8. Community Samples - Accept community-contributed examples

See ROADMAP.md for complete plans.


πŸ“‚ Complete Sample Catalog

Beginner Level (3 Samples) - 1,937 Lines

Perfect for those new to polymorphism and type systems:

# Sample Lines Description Key Concepts
1 PolymorphismBasics 530 Introduction to polymorphism Virtual methods, inheritance
2 CastingExamples 1,075 Upcasting, downcasting, is, as Type casting, pattern matching
3 OverrideVirtual 332 Method overriding in depth override, new, sealed keywords

Intermediate Level (3 Samples) - 3,966 Lines

Advanced OOP concepts with performance considerations:

# Sample Lines Description Key Concepts
4 CovarianceContravariance 1,217 Generic variance in, out, variance
5 BoxingPerformance 2,235 Boxing/unboxing + benchmarks Performance, memory
6 GenericConstraints 514 where T : constraints Generic constraints

Advanced Level (5 Samples) - 11,374 Lines

Production-ready patterns and enterprise architecture:

# Sample Lines Description Key Concepts
7 DesignPatterns 4,501 9 GoF patterns Factory, Builder, Strategy, etc.
8 SOLIDPrinciples 4,714 SOLID with violations + correct SRP, OCP, LSP, ISP, DIP
9 PerformanceOptimization 1,448 Span, Memory, benchmarks Zero-allocation patterns
10 ResiliencePatterns 280 Polly 8.x patterns Retry, Circuit Breaker
11 ObservabilityPatterns 431 Serilog, OpenTelemetry Logging, tracing, metrics

Expert Level (4 Samples) - 1,988 Lines

Cutting-edge C# features and compiler technology:

# Sample Lines Description Key Concepts
12 SourceGenerators 1,042 Custom source generators Roslyn, code generation
13 RoslynAnalyzers 240 Custom analyzers & fixes Diagnostics, code fixes
14 NativeAOT 309 Native AOT compilation Trimming, reflection-free
15 AdvancedPerformance 397 SIMD, parallelism Vectorization, intrinsics

Real-World Level (3 Samples) - 2,563 Lines

Production-ready applications you can deploy:

# Sample Lines Description Key Concepts
16 MLNetIntegration 788 ML.NET integration Classification, regression
17 MicroserviceTemplate 897 Clean architecture CQRS, MediatR, DDD
18 WebApiAdvanced 878 Production Web API JWT, rate limiting, caching

Total: 21,828 lines of educational code across 18 complete samples!


Built with ❀️ by developers passionate about high-performance C# and modern programming practices.

πŸš€ Ready to ship to production!

View Code β€’ Report Bug β€’ Request Feature

Packages

 
 
 

Contributors 3

  •  
  •  
  •  

Languages