Want immutable objects but constructors with 10 parameters are ugly? Use init accessors. Old Way – Constructor Overload Hell: public class Person { public string Name { get; } public int Age { get; } public string Email { get; } public Person(string name, int age, string email) { Name = name; Age = age; […]
Tag: C# Tips
C#: Use Index and Range Operators for Cleaner Array Slicing
Array slicing with loops or LINQ is verbose. C# 8+ has Python-like syntax. Old Way: var numbers = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Get last element var last = numbers[numbers.Length – 1]; // 9 // Get last 3 elements var lastThree = numbers.Skip(numbers.Length – 3).ToArray(); // […]
C#: Use Null-Coalescing Assignment to Simplify Lazy Initialization
Checking if null before initializing is verbose. Use ??= operator for clean lazy initialization. Old Verbose Way: private List _cache; public List GetCache() { if (_cache == null) { _cache = new List(); } return _cache; } Clean Way: private List _cache; public List GetCache() { _cache ??= new List(); return _cache; } // If […]
C#: Use Target-Typed new Expressions to Reduce Verbosity
Stop repeating type names when it’s obvious from context. Use target-typed new. Verbose: Dictionary data = new Dictionary(); Person person = new Person(); List names = new List() { “John”, “Jane” }; Concise: Dictionary data = new(); Person person = new(); List names = new() { “John”, “Jane” }; Type inferred from left side. Less […]
C#: Use nameof Operator to Avoid Magic Strings
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() […]
C#: Use String Interpolation with Alignment for Formatted Output
Aligning console output without string.Format mess? String interpolation supports alignment. Basic Alignment: var name = “John”; var age = 30; Console.WriteLine($”{name,10} | {age,5}”); // Output: ” John | 30″ // Right-aligned, 10 chars for name, 5 for age Left-Align with Negative: Console.WriteLine($”{name,-10} | {age,-5}”); // Output: “John | 30 ” Combined with Formatting: var price […]
.NET Core: Use File-Scoped Namespaces to Reduce Indentation
Tired of extra indentation from namespace blocks? Use file-scoped namespaces. Old Way: namespace MyApp.Services { public class ProductService { public void DoSomething() { // Code here } } } // Everything indented one level New Way (.NET 6+): namespace MyApp.Services; public class ProductService { public void DoSomething() { // Code here – one less indent […]
C#: Use Source Generators to Generate Boilerplate Code at Compile Time
Writing repetitive mapping code, serialization logic, or validators? Source Generators create code at compile time, eliminating runtime reflection overhead. What Are Source Generators: // You write this: [GenerateToString] public partial class Person { public string Name { get; set; } public int Age { get; set; } } // Source Generator automatically creates this at […]
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 […]
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# Records: Immutable Data Classes with Built-In Value Equality (C# 9+)
Tired of writing boilerplate Equals, GetHashCode, and ToString methods? C# records do it automatically with better performance. Old Way – Traditional Class: // BAD: 60+ lines for simple data class public class Person { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } […]
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, […]
C# Performance: Use Span and Memory to Eliminate Array Allocations
Processing large arrays or strings eating up memory? Span<T> lets you work with slices of memory without allocating new arrays. The Problem – Traditional Approach: // BAD: Creates new array on every call public byte[] ProcessChunk(byte[] data, int start, int length) { byte[] chunk = new byte[length]; // Heap allocation Array.Copy(data, start, chunk, 0, length); […]











