Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access

Tag: C# Tips

C#

C#: Use init Accessor to Create Immutable Objects Without Constructor Boilerplate

- 13.02.26 - ErcanOPAK comment on C#: Use init Accessor to Create Immutable Objects Without Constructor Boilerplate

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; […]

Read More
C#

C#: Use Index and Range Operators for Cleaner Array Slicing

- 13.02.26 - ErcanOPAK comment on 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(); // […]

Read More
C#

C#: Use Null-Coalescing Assignment to Simplify Lazy Initialization

- 13.02.26 - ErcanOPAK comment on 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 […]

Read More
C#

C#: Use Target-Typed new Expressions to Reduce Verbosity

- 13.02.26 - ErcanOPAK comment on 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 […]

Read More
C#

C#: Use nameof Operator to Avoid Magic Strings

- 13.02.26 - ErcanOPAK comment on 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() […]

Read More
C#

C#: Use String Interpolation with Alignment for Formatted Output

- 13.02.26 - ErcanOPAK comment on 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 […]

Read More
Asp.Net Core

.NET Core: Use File-Scoped Namespaces to Reduce Indentation

- 13.02.26 - ErcanOPAK comment on .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 […]

Read More
C#

C#: Use Source Generators to Generate Boilerplate Code at Compile Time

- 03.02.26 - ErcanOPAK comment on 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 […]

Read More
C#

C#: Use Record Types with With-Expressions for Immutable Data Transformations

- 03.02.26 - ErcanOPAK comment on 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 […]

Read More
C#

C# String Interpolation: Use $”” for Readability, StringBuilder for Performance

- 01.02.26 - ErcanOPAK comment on 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 […]

Read More
C#

LINQ Performance Trap: Why .Any() Is 10,000x Faster Than .Count() > 0

- 01.02.26 - ErcanOPAK comment on 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: […]

Read More
C#

C# Records: Immutable Data Classes with Built-In Value Equality (C# 9+)

- 01.02.26 | 01.02.26 - ErcanOPAK comment on 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; } […]

Read More
C#

C#: Async/Await Common Mistakes That Kill Performance (And How to Fix Them)

- 01.02.26 | 01.02.26 - ErcanOPAK comment on 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, […]

Read More
C#

C# Performance: Use Span and Memory to Eliminate Array Allocations

- 01.02.26 | 01.02.26 - ErcanOPAK comment on 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); […]

Read More
February 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
232425262728  
« Jan    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (934)
  • How to add default value for Entity Framework migrations for DateTime and Bool (830)
  • Get the First and Last Word from a String or Sentence in SQL (822)
  • How to select distinct rows in a datatable in C# (799)
  • How to make theater mode the default for Youtube (708)
  • Add Constraint to SQL Table to ensure email contains @ (572)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (552)
  • Average of all values in a column that are not zero in SQL (517)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (473)
  • Find numbers with more than two decimal places in SQL (436)

Recent Posts

  • C#: Use init Accessor to Create Immutable Objects Without Constructor Boilerplate
  • C#: Use Index and Range Operators for Cleaner Array Slicing
  • C#: Use Null-Coalescing Assignment to Simplify Lazy Initialization
  • SQL: Use CHAR Instead of VARCHAR for Fixed-Length Columns to Save Space
  • SQL: Use CROSS APPLY Instead of Subqueries for Better Performance
  • .NET Core: Use Required Modifier to Force Property Initialization
  • .NET Core: Use Global Using Directives to Avoid Repeating Imports
  • Git: Use git restore to Unstage Files Without Losing Changes
  • Git: Use git bisect to Find Which Commit Introduced a Bug
  • AJAX: Use Fetch with Signal to Cancel Requests When User Navigates Away

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (934)
  • How to add default value for Entity Framework migrations for DateTime and Bool (830)
  • Get the First and Last Word from a String or Sentence in SQL (822)
  • How to select distinct rows in a datatable in C# (799)
  • How to make theater mode the default for Youtube (708)

Recent Posts

  • C#: Use init Accessor to Create Immutable Objects Without Constructor Boilerplate
  • C#: Use Index and Range Operators for Cleaner Array Slicing
  • C#: Use Null-Coalescing Assignment to Simplify Lazy Initialization
  • SQL: Use CHAR Instead of VARCHAR for Fixed-Length Columns to Save Space
  • SQL: Use CROSS APPLY Instead of Subqueries for Better Performance

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com