class MyClass {
public MyClass() : this(10) { }
public MyClass(int x) { }
}
int[][] jagged = new int[3][];
jagged[0] = new int[] { 1, 2 };
interface IExample {
void Method();
}
class Resource : IDisposable {
public void Dispose() { }
}
delegate void D();
D d = () => Console.WriteLine("A");
d += () => Console.WriteLine("B");
d();
abstract class MyClass { }
class MyClass {
public int X;
}
MyClass c1 = new MyClass { X = 10 };
MyClass c2 = (MyClass)c1.MemberwiseClone(); // Shallow
abstract class Base {
public virtual void Method() { }
}
static IEnumerable Where(this IEnumerable source, Func predicate) {
foreach (var item in source)
if (predicate(item))
yield return item;
}
WeakReference wr = new WeakReference(new object());
volatile int x;
class Resource : IDisposable {
public void Dispose() { }
~Resource() { }
}
#define DEBUG
#if DEBUG
Console.WriteLine("Debug");
#endif
using System;
using System.Collections.Generic;
public record Address(string Street, string City); // Value Object
public class Order // Entity and Aggregate Root
{
public Guid Id { get; private set; }
private List _items = new List();
public IReadOnlyList Items => _items.AsReadOnly();
private Order() { }
public static Order Create() => new Order { Id = Guid.NewGuid() };
public void AddItem(string product, decimal price)
{
_items.Add(new OrderItem(product, price));
DomainEvents.Raise(new OrderItemAdded(Id, product));
}
}
public class OrderItem // Entity within Aggregate
{
public string Product { get; private set; }
public decimal Price { get; private set; }
public OrderItem(string product, decimal price) => (Product, Price) = (product, price);
}
public interface IOrderRepository
{
Task GetByIdAsync(Guid id);
Task SaveAsync(Order order);
}
public static class DomainEvents
{
private static readonly List> _handlers = new List>();
public static void Register(Action handler) => _handlers.Add(e => handler((T)e));
public static void Raise(T @event) => _handlers.ForEach(h => h(@event));
}
public class OrderItemAdded
{
public Guid OrderId { get; }
public string Product { get; }
public OrderItemAdded(Guid orderId, string product) => (OrderId, Product) = (orderId, product);
}
class Program
{
static void Main()
{
DomainEvents.Register(e => Console.WriteLine($"Item {e.Product} added to order {e.OrderId}"));
var order = Order.Create();
order.AddItem("Book", 29.99m);
}
}
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
public interface IService { Task GetDataAsync(); }
public class Service : IService
{
public Task GetDataAsync() => Task.FromResult("Data");
}
public class CachedService : IService
{
private readonly IService _inner;
private readonly IMemoryCache _cache;
private readonly ILogger _logger;
public CachedService(IService inner, IMemoryCache cache, ILogger logger)
{
_inner = inner;
_cache = cache;
_logger = logger;
}
public async Task GetDataAsync()
{
if (_cache.TryGetValue("data", out string cachedData))
{
_logger.LogInformation("Cache hit");
return cachedData;
}
_logger.LogInformation("Cache miss, fetching data");
var data = await _inner.GetDataAsync();
_cache.Set("data", data, TimeSpan.FromMinutes(5));
return data;
}
}
class Program
{
static async Task Main()
{
var services = new ServiceCollection();
services.AddMemoryCache();
services.AddLogging(builder => builder.AddConsole());
services.AddSingleton();
services.Decorate();
var provider = services.BuildServiceProvider();
var service = provider.GetService();
Console.WriteLine(await service.GetDataAsync()); // Data
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
class Program
{
static async Task Main()
{
// IEnumerable: In-memory
var numbers = new List { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
Console.WriteLine("IEnumerable: " + string.Join(", ", evenNumbers)); // 2, 4
// IQueryable: Database query
var dbContext = new MyDbContext();
var query = dbContext.Users.Where(u => u.Age > 18);
var adults = await query.ToListAsync();
Console.WriteLine("IQueryable: " + adults.Count);
// IAsyncEnumerable: Streaming
await foreach (var item in GetDataAsync())
{
Console.WriteLine("IAsyncEnumerable: " + item);
}
}
static async IAsyncEnumerable GetDataAsync()
{
for (int i = 1; i <= 3; i++)
{
await Task.Delay(100);
yield return i;
}
}
}
class MyDbContext : DbContext
{
public DbSet Users { get; set; }
}
class User { public int Age { get; set; } }
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
// Correct: Fully async
var client = new HttpClient();
var data = await client.GetStringAsync("https://example.com").ConfigureAwait(false);
Console.WriteLine(data.Length);
// Avoid: Blocking call
// var result = client.GetStringAsync("https://example.com").Result; // Risk of deadlock
// High-performance with ValueTask
async ValueTask ComputeAsync(int x)
{
if (x < 0) return 0; // Synchronous completion
await Task.Delay(100).ConfigureAwait(false);
return x * 2;
}
Console.WriteLine(await ComputeAsync(5)); // 10
}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddApiVersioning(options =>
{
options.ReportApiVersions = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints => endpoints.MapControllers());
}
}
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok(new { Version = "1.0", Data = "Users" });
}
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class UsersV2Controller : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok(new { Version = "2.0", Data = "Enhanced Users" });
}
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
// Task.Run: Simple async work
await Task.Run(() => Console.WriteLine("Task.Run: " + Thread.CurrentThread.ManagedThreadId));
// Task.Factory.StartNew: Custom options
await Task.Factory.StartNew(() => Console.WriteLine("StartNew: " + Thread.CurrentThread.ManagedThreadId),
TaskCreationOptions.LongRunning);
// ThreadPool.QueueUserWorkItem: Legacy
ThreadPool.QueueUserWorkItem(state => Console.WriteLine("QueueUserWorkItem: " + Thread.CurrentThread.ManagedThreadId));
await Task.Delay(1000); // Allow ThreadPool to execute
}
}
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
private static readonly object _lock = new object();
private static int _counter = 0;
private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(2);
private static readonly Mutex _mutex = new Mutex();
static void Main()
{
// Lock
Parallel.For(0, 5, _ =>
{
lock (_lock)
{
_counter++;
Console.WriteLine($"Lock: {_counter}");
}
});
// Monitor
Monitor.TryEnter(_lock, TimeSpan.FromSeconds(1), ref bool lockTaken);
if (lockTaken)
{
try { _counter++; Console.WriteLine($"Monitor: {_counter}"); }
finally { Monitor.Exit(_lock); }
}
// Mutex (cross-process)
if (_mutex.WaitOne(1000))
{
try { Console.WriteLine("Mutex acquired"); }
finally { _mutex.ReleaseMutex(); }
}
// Semaphore
Parallel.For(0, 5, async _ =>
{
await _semaphore.WaitAsync();
try { Console.WriteLine("Semaphore: Processing"); await Task.Delay(100); }
finally { _semaphore.Release(); }
}).Wait();
}
}
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
public interface IPlugin
{
string Execute();
}
public class PluginHost
{
public static void LoadPlugins(string pluginPath)
{
var context = new AssemblyLoadContext("PluginContext", true);
foreach (var dll in Directory.GetFiles(pluginPath, "*.dll"))
{
try
{
var assembly = context.LoadFromAssemblyPath(Path.GetFullPath(dll));
var plugins = assembly.GetTypes()
.Where(t => typeof(IPlugin).IsAssignableFrom(t) && !t.IsInterface)
.Select(t => (IPlugin)Activator.CreateInstance(t));
foreach (var plugin in plugins)
{
Console.WriteLine($"Plugin Output: {plugin.Execute()}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error loading plugin {dll}: {ex.Message}");
}
}
context.Unload();
}
}
// Example Plugin (in a separate DLL)
public class SamplePlugin : IPlugin
{
public string Execute() => "Hello from SamplePlugin!";
}
class Program
{
static void Main()
{
PluginHost.LoadPlugins("./Plugins");
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
class Program
{
static void Main()
{
// Memory Leak: Event handler
var publisher = new Publisher();
var subscriber = new Subscriber(publisher); // Subscriber stays alive
// Fixed: Unsubscribe
var safeSubscriber = new SafeSubscriber(publisher);
safeSubscriber.Dispose(); // Unsubscribes
// Memory Leak: Static cache
Cache.Add("key", new object());
// Fixed: Bounded cache
using (var cache = new BoundedCache())
{
cache.Add("key", new object());
}
GC.Collect();
Console.WriteLine("GC completed");
}
}
public class Publisher
{
public event EventHandler SomethingHappened;
public void RaiseEvent() => SomethingHappened?.Invoke(this, EventArgs.Empty);
}
public class Subscriber
{
public Subscriber(Publisher publisher)
{
publisher.SomethingHappened += OnSomethingHappened;
}
private void OnSomethingHappened(object sender, EventArgs e) => Console.WriteLine("Event received");
}
public class SafeSubscriber : IDisposable
{
private readonly Publisher _publisher;
public SafeSubscriber(Publisher publisher)
{
_publisher = publisher;
_publisher.SomethingHappened += OnSomethingHappened;
}
private void OnSomethingHappened(object sender, EventArgs e) => Console.WriteLine("Event received");
public void Dispose() => _publisher.SomethingHappened -= OnSomethingHappened;
}
public static class Cache
{
private static readonly List
using System;
class Program
{
static void Main()
{
// Gen 0: Short-lived
var tempList = new List { 1, 2, 3 };
Console.WriteLine("Temp list created");
// Gen 2: Long-lived
static var cache = new List();
cache.AddRange(tempList);
// Force GC to demonstrate
GC.Collect();
Console.WriteLine("GC triggered");
// Disposable pattern for unmanaged resources
using (var resource = new Resource())
{
Console.WriteLine("Using resource");
}
}
}
class Resource : IDisposable
{
public void Dispose() => Console.WriteLine("Resource disposed");
}