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#

Asp.Net Core / C#

C# Records — Why They Still Beat Classes for Domain Models

- 05.12.25 | 05.12.25 - ErcanOPAK comment on C# Records — Why They Still Beat Classes for Domain Models

Records are still the cleanest way to model immutable domain data. public record Order(int Id, decimal Total, string Status); ❤️ Why Devs Love Records 🔐 Built-in immutability 📝 Value-based equality ✂ Boilerplate goes to zero 🔄 Perfect for event-driven + DDD ⚡ Extra Tip Use with expressions to clone deeply but safely.

Read More
Asp.Net Core / C#

.NET 9 Rate Limiting — Easy API Protection

- 05.12.25 | 05.12.25 - ErcanOPAK comment on .NET 9 Rate Limiting — Easy API Protection

Rate limiting used to be hard… now it’s literally one line. app.UseRateLimiter(new() { GlobalLimiter = PartitionedRateLimiter.CreateChained( PartitionedRateLimiter.CreateFixedWindow(10, TimeSpan.FromSeconds(5)) ) }); 🔒 Why You Need It 🛡 Stops brute-force 📉 Protects API throughput ⚙ Cloud-native resilience 🌍 Zero-config distributed support (Redis optional) 🧠 Bonus Pair with Minimal APIs for super-light API services.

Read More
Asp.Net Core / C#

Async Streams in C# — Clean, Fast, Real-Time Data

- 05.12.25 | 05.12.25 - ErcanOPAK comment on Async Streams in C# — Clean, Fast, Real-Time Data

🌀 Why Async Streams Shine Async Streams (IAsyncEnumerable<T>) are perfect for streaming data without memory blows. await foreach (var log in service.GetLogsAsync()) { Console.WriteLine(log); } ✨ What They Solve 🔁 Handling live logs 📡 Streamed API responses 🧵 Reducing memory spikes 🌊 Backpressure-friendly async flow 💡 Pro Tip Combine with channels for ultra-responsive pipelines.

Read More
.NET / Asp.Net Core / C#

EF Core 8 ExecuteUpdate – Batch Updates Without Loops

- 04.12.25 | 04.12.25 - ErcanOPAK

ExecuteUpdate allows batch updates without tracking overhead. await ctx.Users .Where(u => u.IsActive == false) .ExecuteUpdateAsync(p => p.SetProperty(x => x.IsDeleted, true));   It’s fast, clean, and ideal for big-data operations.

Read More
.NET / Asp.Net Core / C#

Cleaner .NET APIs Using IEndpointFilter for Validation

- 04.12.25 | 04.12.25 - ErcanOPAK

Endpoint filters reduce validation noise in Minimal APIs. public class ValidateFilter : IEndpointFilter { public Task<object?> InvokeAsync(EndpointFilterInvocationContext ctx, EndpointFilterDelegate next) { var model = ctx.GetArgument(0); Validator.ValidateObject(model, new()); return next(ctx); } } They keep endpoints clean, reusable, and testable.

Read More
.NET / Asp.Net Core / C#

Build Clean Background Services with IHostedService in .NET

- 04.12.25 | 04.12.25 - ErcanOPAK

BackgroundService enables clean, scalable background processing. protected override async Task ExecuteAsync(CancellationToken ct) { while (!ct.IsCancellationRequested) { await DoWork(); await Task.Delay(1000, ct); } } It works perfectly in cloud-native environments.

Read More
.NET / Asp.Net Core / C# / Entity Framework

Stop Calling ToList() Too Early – Improve LINQ Performance

- 04.12.25 | 04.12.25 - ErcanOPAK

Calling ToList() too early forces premature execution. // Bad var items = db.Users.ToList().Where(…); // Good var items = db.Users.Where(…).ToList();   Let the database handle filtering and execution.

Read More
.NET / Asp.Net Core / C#

Never Write Retry Logic Again – Use Polly in .NET

- 04.12.25 | 04.12.25 - ErcanOPAK

Polly provides retry, timeout, fallback, and circuit-breaker patterns. var result = await Policy .Handle() .RetryAsync(3) .ExecuteAsync(() => CallApi()); It’s the gold standard for resilience in .NET microservices.

Read More
.NET / Asp.Net Core / C#

Clean Minimal APIs in .NET – Automatic DTO Binding Explained

- 04.12.25 | 04.12.25 - ErcanOPAK

Minimal APIs provide automatic DTO binding, eliminating unnecessary boilerplate. app.MapPost(“/login”, (LoginRequest req) => { return Results.Ok($”Welcome {req.Email}”); }); This improves readability, reduces errors, and works perfectly with endpoint filters.

Read More
.NET / Asp.Net Core / C#

Write Cleaner Business Logic Using C# Switch Expressions

- 04.12.25 | 04.12.25 - ErcanOPAK

Switch expressions simplify complex branching logic and make code more readable. var price = plan switch { “free” => 0, “pro” => 19, “biz” => 49, _ => throw new Exception(“Unknown plan”) }; They are ideal for pricing models, rules engines, and state transitions.

Read More
.NET / Asp.Net Core / C#

EF Core Performance Boost: Use AsNoTracking() When Reading Data

- 04.12.25 | 04.12.25 - ErcanOPAK

For read-heavy queries, AsNoTracking() provides massive performance improvements. var users = await ctx.Users.AsNoTracking().ToListAsync(); It avoids adding entities to the change tracker, improving speed by 30–50%.

Read More
.NET / Asp.Net Core / C#

Use IAsyncEnumerable for Streaming Data in .NET

- 04.12.25 | 04.12.25 - ErcanOPAK

IAsyncEnumerable allows true async streaming, reducing memory usage. await foreach (var user in repo.GetAllAsync()) Console.WriteLine(user.Name); Perfect for large datasets and high-throughput APIs.

Read More
.NET / Asp.Net Core / C#

Why C# Record Types Are Perfect for Modern DTOs

- 04.12.25 | 04.12.25 - ErcanOPAK

Records offer immutability, value semantics, and minimal syntax. public record UserDto(int Id, string Name, string Email); They are ideal for APIs, events, and data-transfer layers.

Read More
.NET / Asp.Net Core / C#

Improve .NET Logging with Structured Log Messages

- 04.12.25 | 04.12.25 - ErcanOPAK

Structured logs allow smarter querying and cleaner search results. logger.LogInformation(“User {UserId} logged in”, id); They improve observability, diagnostics, and production monitoring.

Read More
.NET / Asp.Net Core / C#

Boost Async Performance in .NET with ConfigureAwait(false)

- 04.12.25 | 04.12.25 - ErcanOPAK

Using ConfigureAwait(false) can significantly reduce context-switching overhead in non-UI .NET applications. This is essential for APIs, background services, and any high-throughput async pipeline. await http.SendAsync(req).ConfigureAwait(false); It lowers CPU usage, avoids deadlocks, and improves overall async performance.

Read More
.NET / Asp.Net Core / C#

Lightning-Fast Lookups in .NET Using MemoryCache

- 04.12.25 | 04.12.25 - ErcanOPAK

MemoryCache provides a simple and fast in-memory caching solution. var item = cache.GetOrCreate(“users”, entry => { entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10); return repo.GetUsers(); }); Ideal for configuration, lookups, and session data.

Read More
.NET / Asp.Net Core / C#

Every Async Method Should Accept CancellationToken

- 04.12.25 | 04.12.25 - ErcanOPAK

CancellationToken prevents zombie tasks and ensures graceful shutdown. public Task RunAsync(CancellationToken ct) It is a must-have for cloud-native workloads.

Read More
C#

Easy way to join strings on complex classes

- 06.04.24 - ErcanOPAK comment on Easy way to join strings on complex classes

Let’s say you have a class like that: public class Student { public string Name { get; set; } public string Surname { get; set; } public DateTime DateCreated { get; set; } … } If you want to join the name values of that class then you can use the code below: using System.Linq […]

Read More
C#

How to remove all non alphanumeric characters from a string in C#

- 28.09.23 - ErcanOPAK comment on How to remove all non alphanumeric characters from a string in C#

Replace [^a-zA-Z0-9] with an empty string. string str = “This-is-my+++***RegexPattern&Text”; Regex rgx = new Regex(“[^a-zA-Z0-9]”); str = rgx.Replace(str, “”); OUTPUT: ThisismyRegexPatternText If you want to add an exception then you should add this character like this to the regex pattern (let’s assume you wish to exclude the ampersand): [^a-zA-Z0-9 &] string str = “This-is-my+++***RegexPattern&Text”; Regex rgx = […]

Read More
C#

How to get the Xth Day of the Week of the Year in C#

- 25.09.23 - ErcanOPAK comment on How to get the Xth Day of the Week of the Year in C#

Let’s say we want to find the date of the first Friday of the 1st month. GetFirstFridayOfMonth(01.01.2023) =>06.01.2023 (The first Friday after 01.01.2023 is 06.01.2023) public DateTime GetFirstFridayOfMonth(DateTime date) { DateTime fridayDate = new DateTime(date.Year, date.Month, 1); //Let’s assume 1st Friday can start on the 1st of the month while (fridayDate.DayOfWeek != DayOfWeek.Friday) { fridayDate […]

Read More
C#

How to get formatted JSON in C#

- 23.09.23 | 23.09.23 - ErcanOPAK comment on How to get formatted JSON in C#

Like converting XML to Json or Json to XML, you can also use Newtonsoft to get formatted Json. private static string FormatJson(string json) { dynamic parsedJson = JsonConvert.DeserializeObject(json); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } Note: You can use var instead of dynamic. Both will work.

Read More
C#

How to convert JSON to XML or XML to JSON in C#

- 23.09.23 | 23.09.23 - ErcanOPAK comment on How to convert JSON to XML or XML to JSON in C#

To do that easily, you can use Newtonsoft. // To convert an XML node contained in string xml into a JSON string XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); string jsonText = JsonConvert.SerializeXmlNode(doc); // To convert JSON text contained in string json into an XML node XmlDocument doc = JsonConvert.DeserializeXmlNode(json); You can get more info from […]

Read More
ASP.Net MVC / C# / Entity Framework

How to get rows count in EntityFramework without loading contents

- 20.06.23 - ErcanOPAK comment on How to get rows count in EntityFramework without loading contents

Query syntax: var count = (from t in context.MyTable where t.Id == @Id select t).Count(); Method syntax: var count = context.MyTable .Where(t => t.Id == @Id) .Count() Both generate the same SQL query.

Read More
C#

How to use TrimEnd to remove last character from string in C#

- 11.03.23 | 11.03.23 - ErcanOPAK comment on How to use TrimEnd to remove last character from string in C#

string useOfTrimEnd1= “Hello World !”.TrimEnd(‘!’); OUTPUT: Hello World string useOfTrimEnd2= “Hello World !!!!!!”.TrimEnd(‘!’); OUTPUT: Hello World Definition from Microsoft.com: TrimEnd(Char) Removes all the trailing occurrences of a character from the current string. TrimEnd() Removes all the trailing white-space characters from the current string. TrimEnd(Char[]) Removes all the trailing occurrences of a set of characters specified […]

Read More
C#

What is the difference between “int” and “uint” / “long” and “ulong”?

- 10.03.23 | 10.03.23 - ErcanOPAK comment on What is the difference between “int” and “uint” / “long” and “ulong”?

The primitive data types prefixed with “u” are unsigned versions with the same bit sizes. Effectively, this means they cannot store negative numbers, but on the other hand, they can store positive numbers twice as large as their signed counterparts. The signed counterparts do not have “u” prefixed.   The limits for int (32-bit) are: […]

Read More
C#

What is the difference between ‘ref’ and ‘out’ keywords in C#

- 14.01.23 - ErcanOPAK comment on What is the difference between ‘ref’ and ‘out’ keywords in C#

The best way to understand that difference is to show it in code. Let’s say we have an ‘Add’ function. And the only thing that method does is add 10 to the parameter value. static void Main (string[] args) { int myParameter = 20; Add(myParameter); Console.WriteLine(myParameter); } static void Add(int myParameter) { myParameter = myParameter […]

Read More
C#

What is the difference between HashSet and List in .net?

- 07.01.23 - ErcanOPAK comment on What is the difference between HashSet and List in .net?

Unlike a List<> A HashSet is a List with no duplicate members. Because a HashSet is constrained to contain only unique entries, the internal structure is optimized for searching (compared with a list) – it is considerably faster Adding to a HashSet returns a boolean – false if addition fails due to already existing in […]

Read More
C#

What is the purpose of nameof in C#?

- 03.01.23 - ErcanOPAK comment on What is the purpose of nameof in C#?

The purpose of nameof is refactoring. For example, when you change the name of a class to which you refer through nameof somewhere else in your code you will get a compilation error which is what you want. If you didn’t use nameof and had just a plain string as a reference you’d have to full-text […]

Read More
C# / LINQ

What is the difference between Select and SelectMany in Linq

- 30.12.22 - ErcanOPAK comment on What is the difference between Select and SelectMany in Linq

The formal description for SelectMany() is: Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence. SelectMany() flattens the resulting sequences into one sequence and invokes a result selector function on each element. The main difference is the result of each method while SelectMany() returns flattened results; Select() […]

Read More
C#

The Ternary Operator in C# (?:)

- 13.12.22 - ErcanOPAK comment on The Ternary Operator in C# (?:)

C# includes a decision-making operator ?: called the conditional operator or ternary operator. It is the short form of the if-else conditions. Syntax: condition ? statement 1 : statement 2 The ternary operator starts with a boolean condition. If this condition evaluates to true then it will execute the first statement after ?, otherwise the second statement after : will […]

Read More
Page 15 of 17
« Previous 1 … 10 11 12 13 14 15 16 17 Next »

Posts pagination

« Previous 1 … 13 14 15 16 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 (898)
  • How to make theater mode the default for Youtube (858)
  • Get the First and Last Word from a String or Sentence in SQL (840)
  • How to select distinct rows in a datatable in C# (814)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (597)
  • Add Constraint to SQL Table to ensure email contains @ (582)
  • 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 (898)
  • How to make theater mode the default for Youtube (858)
  • Get the First and Last Word from a String or Sentence in SQL (840)
  • How to select distinct rows in a datatable in C# (814)

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