Hardcoding property names as strings breaks when you rename. Use nameof for refactor-safe code. Bad: public class Person { public string Name { get; set; } public void UpdateName(string newName) { Name = newName; OnPropertyChanged(“Name”); // Breaks if you rename property! } } Good: OnPropertyChanged(nameof(Name)); // Compiler-verified! If you rename Name property, compiler updates nameof() […]
Tag: C# Best Practices
C# Record Types: Immutable Data Patterns That Eliminate Bugs
Mutable objects causing threading issues? C# 9+ records provide immutable data structures with built-in value semantics. Records vs Classes: When to Use Each // Use RECORDS for: // 1. Immutable data transfer objects (DTOs) // 2. Value objects in domain-driven design // 3. Configuration objects // 4. API request/response models // 5. Event objects in […]
C#: Use Record Types with With-Expressions for Immutable Data Transformations
Modifying objects causes bugs when multiple parts of code reference the same instance. Records with with-expressions create modified copies safely. The Mutable Class Problem: public class Person { public string Name { get; set; } public int Age { get; set; } } var person = new Person { Name = “John”, Age = 30 […]
C# String Interpolation: Use $”” for Readability, StringBuilder for Performance
Building strings in loops? String interpolation is clean but creates a new string on every concatenation. Here’s when to use what. The Readability Winner: // Old way – hard to read string message = “User ” + userName + ” (ID: ” + userId + “) logged in at ” + timestamp; // Modern way […]
C# Pattern Matching: Replace Complex If-Else Chains with Switch Expressions
Nested if-else statements making your code unreadable? C# 9+ switch expressions with pattern matching can reduce 50+ lines to 10. The Old Nightmare: public decimal CalculateDiscount(Customer customer, Order order) { if (customer == null) return 0; if (customer.IsPremium) { if (order.Total > 1000) return order.Total * 0.20m; else if (order.Total > 500) return order.Total * […]
C#: Async/Await Common Mistakes That Kill Performance (And How to Fix Them)
Using async/await everywhere doesn’t automatically make your code faster – it can actually make it slower if done wrong. Here are the critical mistakes. Mistake 1: Async All The Way Down (Unnecessarily): // BAD: Unnecessary async overhead public async Task GetUserIdAsync(string username) { return await Task.FromResult(_cache.Get(username)); // Why async? } // This creates a Task, […]





