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 […]
Tag: Code Optimization
LINQ Performance Trap: Why .Any() Is 10,000x Faster Than .Count() > 0
Using .Count() > 0 to check if a collection has items? You’re forcing LINQ to enumerate the entire collection just to answer a yes/no question. The Performance Killer: var users = dbContext.Users.Where(u => u.IsActive); // BAD: Counts ALL active users first if (users.Count() > 0) { Console.WriteLine(“We have active users”); } // Database query generated: […]
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 * […]


