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
  • Privacy Policy

Category: C#

C#

C#: Use Init-Only Setters for Immutable Objects After Construction

- 30.03.26 - ErcanOPAK comment on C#: Use Init-Only Setters for Immutable Objects After Construction

๐Ÿ”’ Immutable After Creation Want immutable objects but like object initializers? Init-only setters (C# 9) allow setting properties during initialization only. Read-only after construction. The Old Dilemma // Option 1: Mutable properties (not safe) public class Person { public string Name { get; set; } public int Age { get; set; } } var person […]

Read More
C#

C#: Use Expression-Bodied Members for Concise Single-Line Methods

- 30.03.26 - ErcanOPAK comment on C#: Use Expression-Bodied Members for Concise Single-Line Methods

โžก๏ธ Lambda-Style Everything Simple methods with { return x; }? Verbose. Expression-bodied members use => for methods, properties, constructors. One line replaces five. Expression-Bodied Methods // โŒ Traditional method syntax public string GetFullName() { return $”{FirstName} {LastName}”; } // โœ… Expression-bodied method public string GetFullName() => $”{FirstName} {LastName}”; // More examples public int Add(int a, […]

Read More
C#

C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions

- 30.03.26 - ErcanOPAK comment on C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions

๐Ÿ›ก๏ธ No More NullReferenceException NullReferenceException killing your app? Can’t tell if variable can be null? Nullable reference types (C# 8+) make nullability explicit. Compiler warns about potential null errors. The Null Problem // Before nullable reference types public class UserService { public string GetUserName(int userId) { var user = _repository.GetById(userId); // Could return null! return […]

Read More
C#

C#: Use Record Types for Immutable Data Objects

- 30.03.26 - ErcanOPAK comment on C#: Use Record Types for Immutable Data Objects

๐Ÿ“ฆ Value Objects Made Easy DTOs with 50 lines of boilerplate? Equals(), GetHashCode(), ToString()? Record types (C# 9+) are immutable, value-based, with auto-generated methods. One line replaces 50. Traditional Class vs Record // โŒ Traditional class – Lots of boilerplate public class PersonClass { public string Name { get; init; } public int Age { […]

Read More
C#

C#: Use Span for High-Performance Memory Operations

- 22.03.26 - ErcanOPAK comment on C#: Use Span for High-Performance Memory Operations

๐Ÿš€ Zero-Allocation String Operations Substring creates new string. Array slicing copies memory. Span<T> provides zero-copy views. Massive performance gains. The Problem with Substring // โŒ Traditional: Allocates new strings string data = “2024-03-19T10:30:00”; string year = data.Substring(0, 4); // Allocates “2024” string month = data.Substring(5, 2); // Allocates “03” string day = data.Substring(8, 2); // […]

Read More
C#

C#: Async/Await Best Practices – Avoid Common Mistakes

- 22.03.26 - ErcanOPAK comment on C#: Async/Await Best Practices – Avoid Common Mistakes

โšก Async Done Right Async/await is powerful but tricky. Common mistakes cause deadlocks, performance issues, bugs. Learn to do it right. โŒ Mistake 1: Async Void // โŒ BAD: Async void (only for event handlers!) public async void ProcessData() { await DoWorkAsync(); } // Problems: // – Can’t await it // – Exceptions crash app […]

Read More
C#

C#: Use LINQ Efficiently – Avoid Common Performance Pitfalls

- 22.03.26 - ErcanOPAK comment on C#: Use LINQ Efficiently – Avoid Common Performance Pitfalls

โšก LINQ Done Right LINQ is powerful but easy to misuse. Common mistakes make queries 100x slower. Learn to write fast LINQ. โŒ Mistake 1: Multiple Enumerations // โŒ BAD: Query executed 3 times! var query = users.Where(u => u.Age > 18); // Not executed yet (deferred) var count = query.Count(); // Executes query var […]

Read More
C#

C#: Use Pattern Matching for Cleaner Type Checks and Switches

- 22.03.26 - ErcanOPAK comment on C#: Use Pattern Matching for Cleaner Type Checks and Switches

๐ŸŽฏ Switch on Steroids Type casting everywhere? Nested if-else chains? Pattern matching makes type checks and complex conditions elegant. Type Pattern (is) // โŒ Old way: Type check + cast if (obj is string) { string s = (string)obj; Console.WriteLine(s.ToUpper()); } // โœ… Pattern matching: Check and declare in one if (obj is string s) […]

Read More
C#

C#: Use Index and Range for Clean Array Slicing

- 19.03.26 - ErcanOPAK comment on C#: Use Index and Range for Clean Array Slicing

๐Ÿ”ช Slice Arrays Like Python Array.Copy() for slicing? Verbose. Index (^) and Range (..) operators make it elegant. Index from End (^) var numbers = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Old way: Last element var last = numbers[numbers.Length – 1]; // New way: ^1 means “1 […]

Read More
C#

C#: Use Expression-Bodied Members for One-Liners

- 19.03.26 - ErcanOPAK comment on C#: Use Expression-Bodied Members for One-Liners

โœจ Write Less, Express More Simple properties and methods don’t need full syntax. Expression bodies (=>) make code concise. Before: Verbose Syntax public class User { public string FirstName { get; set; } public string LastName { get; set; } // Verbose property public string FullName { get { return $”{FirstName} {LastName}”; } } // […]

Read More
C#

C#: Use Tuples for Multiple Return Values

- 19.03.26 - ErcanOPAK comment on C#: Use Tuples for Multiple Return Values

๐Ÿ“ฆ Return Multiple Values Elegantly Creating class for one method? Using out parameters? Ugly. Tuples return multiple values cleanly. The Old Ways (Painful) // โŒ Out parameters (ugly) public void GetStats(out int count, out decimal total, out decimal avg) { count = 100; total = 5000m; avg = 50m; } // Ugly usage GetStats(out int […]

Read More
C#

C#: Use String Interpolation with Format Specifiers

- 19.03.26 - ErcanOPAK comment on C#: Use String Interpolation with Format Specifiers

๐ŸŽจ Format Strings Like a Pro String.Format() verbose. Concatenation messy. String interpolation with format specifiers = clean & powerful. Common Format Specifiers decimal price = 1234.5678m; DateTime now = DateTime.Now; int count = 42; // Currency Console.WriteLine($”Price: {price:C}”); // Output: Price: $1,234.57 // Fixed decimal places Console.WriteLine($”Price: {price:F2}”); // Output: Price: 1234.57 // Percentage Console.WriteLine($”Progress: […]

Read More
C#

C#: Use CallerArgumentExpression for Better Error Messages

- 19.03.26 | 19.03.26 - ErcanOPAK comment on C#: Use CallerArgumentExpression for Better Error Messages

ArgumentNullException says ‘parameter is null’. Which parameter? // Old way – manual parameter name public void Process(User user) { if (user == null) throw new ArgumentNullException(nameof(user)); } // New way – automatic! (C# 10+) public void Process(User user) { ArgumentNullException.ThrowIfNull(user); // Error message includes actual expression: ‘user’ } // Custom validation public void ValidatePositive( int […]

Read More
C#

C#: Use Target-Typed new for Cleaner Code

- 19.03.26 | 19.03.26 - ErcanOPAK comment on C#: Use Target-Typed new for Cleaner Code

Type name repeated on both sides. Redundant. // โŒ Verbose Dictionary<string, List> dict = new Dictionary<string, List>(); // โœ… Target-typed new (C# 9+) Dictionary<string, List> dict = new(); // Works everywhere List users = new(); var service = new UserService(); return new User { Name = “John” }; // Field initialization private readonly HttpClient _client […]

Read More
C#

C#: Use global using to Import Namespaces Once

- 19.03.26 | 19.03.26 - ErcanOPAK comment on C#: Use global using to Import Namespaces Once

Every file: using System.Linq; using System.Collections.Generic; Global Usings: Import once, available everywhere. // Create Usings.cs global using System; global using System.Linq; global using System.Collections.Generic; global using Microsoft.EntityFrameworkCore; // Now all files in project have these // No need to repeat in every file Implicit Global Usings: Enable in .csproj: enable Common namespaces auto-imported.

Read More
C#

C#: Use File-Scoped Namespaces to Reduce Indentation

- 19.03.26 | 19.03.26 - ErcanOPAK comment on C#: Use File-Scoped Namespaces to Reduce Indentation

Entire file indented one level for namespace. Wasted space. // โŒ Old way (extra indentation) namespace MyApp.Services { public class UserService { public void DoSomething() { // Code here } } } // โœ… File-scoped namespace (C# 10+) namespace MyApp.Services; public class UserService { public void DoSomething() { // Code here – one less indent […]

Read More
C#

C#: Use Span for Zero-Allocation String Operations

- 19.03.26 | 19.03.26 - ErcanOPAK comment on C#: Use Span for Zero-Allocation String Operations

๐Ÿš€ Zero-Copy Strings Substring creates new string (allocation). Span slices without copying. // โŒ Allocates memory string text = “Hello, World!”; string hello = text.Substring(0, 5); // New string // โœ… Zero allocation ReadOnlySpan span = text.AsSpan(); ReadOnlySpan hello = span.Slice(0, 5); // No copy! // Parsing without allocation ReadOnlySpan numbers = “123,456,789”.AsSpan(); var parts […]

Read More
C#

C#: Use required Modifier to Enforce Property Initialization

- 19.03.26 | 19.03.26 - ErcanOPAK comment on C#: Use required Modifier to Enforce Property Initialization

โœ… Compile-Time Validation Forget to set a property? Null reference exception at runtime. Required modifier catches at compile time. // C# 11+ public class User { public required string Name { get; init; } public required string Email { get; init; } public string? Phone { get; init; } // Optional } // โœ… Valid […]

Read More
C#

C#: Use Pattern Matching with switch Expressions

- 19.03.26 | 19.03.26 - ErcanOPAK comment on C#: Use Pattern Matching with switch Expressions

๐ŸŽฏ Modern Switch Old switch statements verbose. Switch expressions compact, powerful. // Old way string result; switch (value) { case 1: result = “One”; break; case 2: result = “Two”; break; default: result = “Other”; break; } // Modern way var result = value switch { 1 => “One”, 2 => “Two”, _ => “Other” […]

Read More
C#

C#: Use init Accessors for Immutable Objects with Object Initializers

- 19.03.26 | 19.03.26 - ErcanOPAK comment on C#: Use init Accessors for Immutable Objects with Object Initializers

๐Ÿ”’ Immutable + Flexible Readonly properties need constructor parameters. Init accessors let you use object initializers. // C# 9+ public class User { public int Id { get; init; } public string Name { get; init; } public string Email { get; init; } } // Can set during initialization var user = new User […]

Read More
C#

C#: Saving Memory with yield return (Lazy Streams)

- 01.03.26 - ErcanOPAK comment on C#: Saving Memory with yield return (Lazy Streams)

Don’t return a List<T> if you only need to iterate over it. Use yield return. This generates the next item only when the caller asks for it, meaning you can process 1 billion records without ever running out of RAM. It’s the magic behind LINQ.

Read More
C#

C#: Why Records are Better Than Classes for Data DTOs

- 01.03.26 - ErcanOPAK comment on C#: Why Records are Better Than Classes for Data DTOs

Tired of writing GetHashCode, Equals, and ToString for your data objects? Use record. public record User(int Id, string Name); var u1 = new User(1, “Ercan”); var u2 = u1 with { Name = “Opak” }; // Immutable transformation! It’s concise, thread-safe, and built specifically for modern data-driven applications.

Read More
C#

C#: Creating Strings Without Memory Pressure with String.Create

- 01.03.26 - ErcanOPAK comment on C#: Creating Strings Without Memory Pressure with String.Create

๐Ÿš€ High Performance C# Standard string concatenation creates too many temporary objects. String.Create allows you to write directly into the string’s buffer. This is a Senior-only optimization for code that runs millions of times per second (like logging frameworks or high-speed serializers).

Read More
C#

C#: Throttling Concurrent Operations with SemaphoreSlim

- 01.03.26 - ErcanOPAK comment on C#: Throttling Concurrent Operations with SemaphoreSlim

If you run 1000 Tasks in parallel, you might overwhelm your DB or external API. Use SemaphoreSlim to limit concurrency. private static SemaphoreSlim _gate = new(5); // Only 5 at a time await _gate.WaitAsync(); try { await CallExternalApi(); } finally { _gate.Release(); }

Read More
C#

C#: Clean Metadata with Generic Attributes

- 01.03.26 - ErcanOPAK comment on C#: Clean Metadata with Generic Attributes

Before C# 11, passing types to attributes was messy ([Service(typeof(IUser))]). Now you can use generics. public class ServiceAttribute : Attribute where T : class { } [ServiceAttribute] public class MyRepo { … } It’s type-safe, cleaner, and allows for better IDE support and refactoring.

Read More
C#

C#: Writing Allocation-Free High Performance Code with Span

- 01.03.26 - ErcanOPAK comment on C#: Writing Allocation-Free High Performance Code with Span

Parsing strings usually creates hundreds of substrings on the heap. Span<T> provides a ‘view’ into memory without copying it. ReadOnlySpan text = “2024-03-01”; var year = text.Slice(0, 4); // Zero allocation! The Impact: This is how the .NET team made the runtime 10x faster in recent versions. Use it for high-frequency string or array processing.

Read More
C#

C#: The Future of AOP – Exploring C# 12 Interceptors

- 01.03.26 - ErcanOPAK comment on C#: The Future of AOP – Exploring C# 12 Interceptors

Interceptors allow you to literally ‘reroute’ a method call to a different piece of code at compile time. This is the ultimate tool for framework builders and Aspect-Oriented Programming (AOP). Imagine replacing a standard Console.WriteLine with a custom logger throughout your entire app without changing a single line of business code. A total game changer […]

Read More
C#

C#: Forcing Performance with MethodImpl (AggressiveInlining)

- 01.03.26 - ErcanOPAK comment on C#: Forcing Performance with MethodImpl (AggressiveInlining)

For micro-optimizations in hot loops, you can ‘hint’ to the JIT compiler to inline a method, removing the overhead of the method call. [MethodImpl(MethodImplOptions.AggressiveInlining)] public int FastAdd(int a, int b) => a + b; Note: Use this sparingly. Inlining too much can increase binary size and actually hurt performance via cache misses.

Read More
C#

C#: Simulating Discriminated Unions with Modern Pattern Matching

- 01.03.26 - ErcanOPAK comment on C#: Simulating Discriminated Unions with Modern Pattern Matching

Handle complex business states (Success, Error, Loading) without messy if-else or null checks. public record Result; public record Success(string Data) : Result; public record Failure(int Code) : Result; string message = result switch { Success s => $”Fetched: {s.Data}”, Failure f => $”Error code: {f.Code}”, _ => “Unknown State” };

Read More
C#

C#: Reducing GC Pressure with ValueTask for Hot Paths

- 28.02.26 - ErcanOPAK comment on C#: Reducing GC Pressure with ValueTask for Hot Paths

Every time you await Task, an object is allocated on the heap. In a high-frequency loop, this causes the Garbage Collector to work too hard. The Fix: Use ValueTask for methods that often complete synchronously. It’s a struct (stored on the stack), resulting in zero allocations for completed results. High-performance libraries like System.Text.Json use this […]

Read More
Page 1 of 14
1 2 3 4 5 6 … 14 Next ยป

Posts navigation

Older posts
April 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
27282930  
« Mar    

Most Viewed Posts

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

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries
  • SQL: Use Window Functions for Advanced Analytical Queries
  • .NET Core: Use Background Services for Long-Running Tasks
  • .NET Core: Use Minimal APIs for Lightweight HTTP Services
  • Git: Use Cherry-Pick to Apply Specific Commits Across Branches
  • Git: Use Interactive Rebase to Clean Up Commit History Before Merge

Most Viewed Posts

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

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries

Social

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