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 Using Statements for Resource Management

- 12.07.26 - ErcanOPAK comment on C#: Use Using Statements for Resource Management

๐Ÿ“ฆ Using = Resource Management Resources leak without cleanup. Using statements ensure disposal. Files, connections, streams โ€” auto-cleanup. โŒ Manual Cleanup var file = File.Open(“file.txt”); try { // Use file } finally { file.Dispose(); } โœ… Using Statement using var file = File.Open(“file.txt”); // Use file – auto-disposed ๐Ÿ“ Using Examples // File operations using […]

Read More
C#

C#: Use Lambda Expressions for Concise Code

- 12.07.26 - ErcanOPAK comment on C#: Use Lambda Expressions for Concise Code

โšก Lambda Expressions = Concise Code Anonymous methods are verbose. Lambda expressions are concise. One-liners for LINQ, delegates, events. โŒ Anonymous Method Func square = delegate(int x) { return x * x; }; โœ… Lambda Expression Func square = x => x * x; ๐Ÿ“ Lambda Examples // Basic syntax (parameters) => expression (parameters) => […]

Read More
C#

C#: Use Extension Methods to Add Functionality

- 12.07.26 - ErcanOPAK comment on C#: Use Extension Methods to Add Functionality

๐Ÿ”Œ Extension Methods = Add Functionality Can’t modify existing types? Extension methods add functionality. Use like instance methods. โŒ Static Methods string email = “USER@EXAMPLE.com”; email = StringHelper.ToTitleCase(email); โœ… Extension Method string email = “USER@EXAMPLE.com”; email = email.ToTitleCase(); ๐Ÿ“ Extension Examples // Static class, static methods public static class StringExtensions { public static string ToTitleCase(this […]

Read More
C#

C#: Use Generics for Type-Safe Code

- 12.07.26 - ErcanOPAK comment on C#: Use Generics for Type-Safe Code

๐Ÿงฉ Generics = Type-Safe Code Object types are unsafe. Generics create type-safe reusable code. Performance, safety, flexibility. โŒ Object (Unsafe) public class Stack { private object[] items; public void Push(object item) { } public object Pop() { } } Stack s = new Stack(); s.Push(123); // Boxed int i = (int)s.Pop(); // Cast โœ… Generic […]

Read More
C#

C#: Use Records for Immutable Data Types

- 12.07.26 - ErcanOPAK comment on C#: Use Records for Immutable Data Types

๐Ÿ“ Records = Immutable Data Classes are mutable. Records are immutable. Value-based equality, concise syntax, data-centric. โŒ Class (Mutable) public class Person { public string Name { get; set; } public int Age { get; set; } } โœ… Record (Immutable) public record Person(string Name, int Age); ๐Ÿ“ Record Features // Positional record public record […]

Read More
C#

C#: Use ValueTuples for Multiple Return Values

- 12.07.26 - ErcanOPAK comment on C#: Use ValueTuples for Multiple Return Values

๐Ÿ“ฆ ValueTuples = Multiple Return Values Returning multiple values is messy. ValueTuples make it clean. Lightweight, named, convenient. โŒ Out Parameters public void GetUser(out int id, out string name) { id = 1; name = “Alice”; } โœ… ValueTuple public (int Id, string Name) GetUser() { return (1, “Alice”); } ๐Ÿ“ ValueTuple Examples // Named […]

Read More
C#

C#: Struct vs Class โ€” Choose Wisely

- 11.07.26 - ErcanOPAK comment on C#: Struct vs Class โ€” Choose Wisely

๐Ÿ“ฆ Struct vs Class โ€” Choose Wisely Both store data. Struct vs Class matters for performance. Value type vs reference type. ๐Ÿ“ Key Differences // Class (Reference Type) public class Person { public string Name { get; set; } public int Age { get; set; } } // Struct (Value Type) public struct Point { […]

Read More
C#

C#: Async/Await Best Practices

- 11.07.26 - ErcanOPAK comment on C#: Async/Await Best Practices

โšก Async/Await Best Practices Async is powerful but tricky. Best practices make it reliable. Performance, deadlocks, error handling. ๐Ÿ“ Best Practices // 1. Use async for I/O only // Good: Database, HTTP, file I/O public async Task GetUserAsync(int id) { … } // Bad: CPU-intensive operations public async Task CalculateAsync(int n) { … } // […]

Read More
C#

C#: Use Task-Based Asynchronous Pattern (TAP)

- 11.07.26 - ErcanOPAK comment on C#: Use Task-Based Asynchronous Pattern (TAP)

โšก TAP = Asynchronous Programming Async is essential. TAP is the standard pattern. Async/await, Task, Task. ๐Ÿ“ TAP Basics // Basic async method public async Task GetDataAsync() { using var client = new HttpClient(); var result = await client.GetStringAsync(“https://api.example.com/data”); return result; } // Async with error handling public async Task GetUserAsync(int id) { try { […]

Read More
C#

C#: Master Exception Handling with Try-Catch

- 11.07.26 - ErcanOPAK comment on C#: Master Exception Handling with Try-Catch

๐Ÿ›ก๏ธ Exception Handling = Robust Code Apps crash without error handling. Try-catch handles errors gracefully. Robust, reliable apps. ๐Ÿ“ Try-Catch Basics try { // Code that might throw int result = int.Parse(input); Console.WriteLine($”Result: {result}”); } catch (FormatException ex) { Console.WriteLine($”Invalid format: {ex.Message}”); } catch (OverflowException ex) { Console.WriteLine($”Number too large: {ex.Message}”); } catch (Exception ex) […]

Read More
C#

C#: Use String Interpolation for Clean Formatting

- 11.07.26 - ErcanOPAK comment on C#: Use String Interpolation for Clean Formatting

๐Ÿ“ String Interpolation = Clean Formatting String concatenation is messy. String interpolation embeds expressions directly. Readable, concise, elegant. โŒ Concatenation string msg = “Hello, ” + name + “. You are ” + age + ” years old. Today is ” + date.ToShortDateString(); โœ… Interpolation string msg = $”Hello, {name}. You are {age} years old. […]

Read More
C#

C#: Use Null-Coalescing Operator (??) for Default Values

- 11.07.26 - ErcanOPAK comment on C#: Use Null-Coalescing Operator (??) for Default Values

?? Null-Coalescing = Default Values Null checks are verbose. Null-coalescing operator provides defaults. Clean, concise, safe. โŒ Verbose Null Check string name; if (user != null && user.Name != null) name = user.Name; else name = “Unknown”; โœ… Null-Coalescing string name = user?.Name ?? “Unknown”; ๐Ÿ“ Null-Coalescing Examples // Null-coalescing (??) string name = user?.Name […]

Read More
C#

C#: Use Records for Immutable Data Types

- 10.07.26 - ErcanOPAK comment on C#: Use Records for Immutable Data Types

๐Ÿ“ Records = Immutable Data Classes are mutable. Records are immutable. Value-based equality, concise syntax, data-centric. โŒ Class (Mutable) public class Person { public string Name { get; set; } public int Age { get; set; } } โœ… Record (Immutable) public record Person(string Name, int Age); ๐Ÿ“ Record Features // Positional record public record […]

Read More
C#

C#: Use Indexers for Array-Like Access

- 10.07.26 - ErcanOPAK comment on C#: Use Indexers for Array-Like Access

๐Ÿ“ Indexers = Array-Like Access Custom collections need array access. Indexers provide array-like syntax. Clean, intuitive, flexible. ๐Ÿ“ Indexer Basics // Simple indexer public class StringCollection { private string[] _items = new string[10]; public string this[int index] { get => _items[index]; set => _items[index] = value; } } // Usage var collection = new StringCollection(); […]

Read More
C#

C#: Use ValueTuple for Lightweight Multiple Return Values

- 10.07.26 - ErcanOPAK comment on C#: Use ValueTuple for Lightweight Multiple Return Values

๐Ÿ“ฆ ValueTuple = Lightweight Tuples Return multiple values without creating classes. ValueTuple is lightweight, value-based, convenient. ๐Ÿ“ฆ Tuple (Reference Type) var result = Tuple.Create(1, “Alice”); int id = result.Item1; string name = result.Item2; โœ… ValueTuple (Value Type) var result = (Id: 1, Name: “Alice”); int id = result.Id; string name = result.Name; ๐ŸŽฏ ValueTuple Examples […]

Read More
C#

C#: Use Object Initializers for Clean Object Creation

- 10.07.26 - ErcanOPAK comment on C#: Use Object Initializers for Clean Object Creation

๐Ÿ“ฆ Object Initializers = Clean Creation Constructors with many params are messy. Object initializers create objects cleanly. Readable, concise, flexible. โŒ Constructor public class User { public string Name { get; set; } public int Age { get; set; } public string Email { get; set; } public User(string name, int age, string email) { […]

Read More
C#

C#: Use Nullable Reference Types for Null Safety

- 10.07.26 - ErcanOPAK comment on C#: Use Nullable Reference Types for Null Safety

๐Ÿ›ก๏ธ Nullable Reference Types = Null Safety Null reference is #1 error. Nullable reference types prevent null bugs. Compiler help, fewer crashes, safer code. ๐Ÿ“ Enabling Nullable # Project file enable # Or per file #nullable enable # Disable nullable #nullable disable # Nullable annotations public class Person { // Non-nullable (compiler warns if null) […]

Read More
C#

C#: Use Pattern Matching for Elegant Code

- 10.07.26 - ErcanOPAK comment on C#: Use Pattern Matching for Elegant Code

๐ŸŽฏ Pattern Matching = Elegant Code If-else chains are messy. Pattern matching is elegant. Switch expressions, type matching, property patterns. ๐Ÿ“ Pattern Types // Type pattern if (obj is string s) { Console.WriteLine($”String: {s}”); } else if (obj is int i) { Console.WriteLine($”Integer: {i}”); } // Property pattern if (person is { Name: “Alice”, Age: […]

Read More
C#

C#: Use File Scoped Namespaces for Cleaner Code

- 09.07.26 - ErcanOPAK comment on C#: Use File Scoped Namespaces for Cleaner Code

๐Ÿ“ File Scoped Namespaces = Cleaner Code Namespaces add indentation. File scoped namespaces are cleaner. Less nesting, more readable. โŒ Old Style namespace MyApp { namespace Models { public class User { } } namespace Services { public class UserService { } } } โœ… File Scoped namespace MyApp.Models; public class User { } namespace […]

Read More
C#

C#: Use Default Interface Methods for API Evolution

- 09.07.26 - ErcanOPAK comment on C#: Use Default Interface Methods for API Evolution

๐Ÿ”Œ Default Interface Methods = API Evolution Interfaces break existing code. Default interface methods add methods without breaking. Evolve APIs safely. ๐Ÿ“ Default Interface Basics // Interface with default method public interface ILogger { void Log(string message); // Default implementation void LogError(string message) { Log($”ERROR: {message}”); } // Default implementation void LogWarning(string message) { Log($”WARNING: […]

Read More
C#

C#: Use Native AOT for High-Performance Apps

- 09.07.26 - ErcanOPAK comment on C#: Use Native AOT for High-Performance Apps

๐Ÿš€ Native AOT = Ultra Performance JIT compilation has overhead. Native AOT compiles ahead-of-time. Fast startup, low memory, native performance. ๐Ÿ“ AOT Setup # Project file <Project Sdk=”Microsoft.NET.Sdk”> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0</TargetFramework> <PublishAot>true</PublishAot> <TrimMode>full</TrimMode> <EnableAotAnalyzer>true</EnableAotAnalyzer> </PropertyGroup> </Project> # Publish with AOT dotnet publish -c Release -r win-x64 –self-contained # Or dotnet publish -c Release -r linux-x64 […]

Read More
C#

C#: Use Source Generators for Code Generation

- 09.07.26 - ErcanOPAK comment on C#: Use Source Generators for Code Generation

โšก Source Generators = Code Generation Boilerplate code is tedious. Source Generators generate code at compile time. Efficiency, consistency, performance. ๐Ÿ“ Source Generator Setup // Create generator project dotnet new console -n MyGenerator cd MyGenerator dotnet add package Microsoft.CodeAnalysis.CSharp dotnet add package Microsoft.CodeAnalysis.Analyzers // Generator class using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Text; using System.Text; [Generator] […]

Read More
C#

C#: Use Span for High-Performance Memory Operations

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

โšก Span = Memory Performance Memory allocations slow down apps. Span provides safe, allocation-free access. High-performance, low-allocation code. ๐Ÿ“ Span Basics // Span from array int[] numbers = {1, 2, 3, 4, 5}; Span span = numbers.AsSpan(); // Slice Span slice = span.Slice(1, 3); // {2, 3, 4} // Modify via span slice[0] = 10; […]

Read More
C#

C#: Use Async Streams for Asynchronous Data Sequences

- 09.07.26 - ErcanOPAK comment on C#: Use Async Streams for Asynchronous Data Sequences

๐ŸŒŠ Async Streams = Asynchronous Data Sync streams block. IAsyncEnumerable is async. Process data as it arrives, non-blocking, efficient. ๐Ÿ“ Async Streams Basics // Async stream method async IAsyncEnumerable GenerateNumbersAsync() { for (int i = 0; i < 10; i++) { await Task.Delay(100); // Simulate async work yield return i; } } // Consume async […]

Read More
C#

C#: Use Nullable Reference Types for Null Safety

- 07.07.26 - ErcanOPAK comment on C#: Use Nullable Reference Types for Null Safety

๐Ÿ›ก๏ธ Nullable Reference Types = Null Safety Null reference is #1 error. Nullable reference types prevent null bugs. Compiler help, fewer crashes, safer code. โŒ Null (Unsafe) public class User { public string Name { get; set; } public string Email { get; set; } } // Potential null reference โœ… Nullable Reference (Safe) public […]

Read More
C#

C#: Use Pattern Matching for Elegant Code

- 07.07.26 - ErcanOPAK comment on C#: Use Pattern Matching for Elegant Code

๐ŸŽฏ Pattern Matching = Elegant Code If-else chains are messy. Pattern matching is elegant. Switch expressions, type matching, property patterns. โŒ If-Else Chains if (obj is string) { … } else if (obj is int) { … } else if (obj is bool) { … } โœ… Pattern Matching switch (obj) { string s => […]

Read More
C#

C#: Use Records for Immutable Data Types

- 07.07.26 - ErcanOPAK comment on C#: Use Records for Immutable Data Types

๐Ÿ“ Records = Immutable Data Classes are mutable. Records are immutable. Value-based equality, concise syntax, data-centric. โŒ Class (Mutable) public class Person { public string Name { get; set; } public int Age { get; set; } } โœ… Record (Immutable) public record Person(string Name, int Age); ๐Ÿ“ Record Features // Positional record public record […]

Read More
C#

C#: Use Using Statements for Resource Management

- 07.07.26 - ErcanOPAK comment on C#: Use Using Statements for Resource Management

๐Ÿ“ฆ Using = Resource Management Resources leak without cleanup. Using statements ensure disposal. Files, connections, streams โ€” cleanup automatically. โŒ Manual Cleanup (Error-Prone) var file = File.Open(“file.txt”); try { // Use file } finally { file.Dispose(); } โœ… Using Statement (Clean) using var file = File.Open(“file.txt”); // Use file – auto-disposed ๐Ÿ“ Using Examples // […]

Read More
C#

C#: Use Lambda Expressions for Concise Code

- 07.07.26 - ErcanOPAK comment on C#: Use Lambda Expressions for Concise Code

โšก Lambdas = Concise Functions Anonymous methods are verbose. Lambda expressions are concise. One-liners for LINQ, delegates, events. โŒ Anonymous Method Func square = delegate(int x) { return x * x; }; โœ… Lambda Expression Func square = x => x * x; ๐Ÿ“ Lambda Syntax // Basic syntax (parameters) => expression (parameters) => { […]

Read More
C#

C#: Use Generics for Type-Safe Reusable Code

- 07.07.26 - ErcanOPAK comment on C#: Use Generics for Type-Safe Reusable Code

๐Ÿงฉ Generics = Type-Safe Code Object types are unsafe. Generics create type-safe reusable code. Performance, safety, flexibility. โŒ Object (Unsafe) public class Stack { private object[] items; public void Push(object item) { } public object Pop() { } } Stack s = new Stack(); s.Push(123); // Boxed int i = (int)s.Pop(); // Cast โœ… Generic […]

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

Posts pagination

1 2 3 … 17 Next »
July 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  
« Jun    

Most Viewed Posts

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

Recent Posts

  • C#: Use Using Statements for Resource Management
  • C#: Use Lambda Expressions for Concise Code
  • SQL: Use GROUP BY for Data Aggregation
  • .NET Core: Master Routing for Clean URLs
  • Git: Use Reset to Undo Local Changes
  • Ajax: Use Axios for HTTP Requests
  • JavaScript: Understand Hoisting
  • HTML: Use Web Storage for Client-Side Data
  • CSS: Use Filter Effects for Visual Magic
  • Windows 11: Unlock God Mode for All Settings

Most Viewed Posts

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

Recent Posts

  • C#: Use Using Statements for Resource Management
  • C#: Use Lambda Expressions for Concise Code
  • SQL: Use GROUP BY for Data Aggregation
  • .NET Core: Master Routing for Clean URLs
  • Git: Use Reset to Undo Local Changes

Social

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