All posts with Tag c#

Preview image blogpost

LINQ might get a "left join" operator in .net 10

LINQ has a Join operator, that basically translates to something like a SQL INNER JOIN. There is no built in operator for a LEFT JOIN in LINQ, but you can achieve the same result by using a combination of GroupJoin, SelectMany and DefaultIfEmpty. But there is a chance that this might change in the future, as there is a proposal to add a LeftJoin operator in .net 10.

Read the whole article

Preview image blogpost

Having fun with ValueTuple

Just as a heads up: This blog post will probably bring you 0 value in your daily life - well, maybe a short smile. Let's put ValueTuple to its extreme!

Read the whole article

Preview image blogpost

"Always use early returns" - LinkedIn Edition

Ahhhh dear LinkedIn - a pool of gems where everyone is expert in everything. Over the time I collected some trophies from there and today I want to discuss one of them: "Always use early returns".

Read the whole article

Preview image blogpost

How to assert assumptions in code that might not be true?

Sometimes we have to make assumptions in our code. For example, that a certain property or variable has a specific value. On top comes, we have a specific idea but we are not 100% sure if they are correct. Let's meet Debug.Assert.

Read the whole article

Preview image blogpost

An awaitable Blazor Modal Dialog

I already showcased a simple modal dialog in a previous post. However, the dialog was not awaitable. In this post, I'll show you how to create an awaitable modal dialog.

Read the whole article

Comparing the performance between the Minimal API and classic Controllers

Today, we are going to benchmark the performance of the Minimal API in ASP.NET 9 (and for reference against ASP.NET 8 as well) against the classic Controllers. We will test a few scenarios and check how the performance of the Minimal API compares to the classic Controllers. Let's get right into it!

Read the whole article

Preview image blogpost

xUnit v3 and some stuff about TUnit

I know that there is a lot of fuse about TUnit and I am here writing about xUnit. I might cover TUnit in the future, but for now, the topic is the v3 prerelease of xUnit!

Read the whole article

Preview image blogpost

Managing TaskCancellationTokens in a central service in ASP.NET

In async code it is very common to pass a CancellationToken to the method that is being awaited. This allows the caller to cancel the operation if it is no longer needed. But this will lead to some ceremonial code that is repeated in every method. In this article I will show you how to manage CancellationToken in a central service in ASP.NET.

Read the whole article

Preview image blogpost

LINQ Joins on multiple columns in Entity Framework

I came across a very annoying "issue" with LINQ joins (left joins) in Entity Framework where the compiler drove me nuts!

Read the whole article

Preview image blogpost

FormattableStringFactory - Creating dynamic FormattableString instances

I recently came across the FormattableStringFactory to create dynamic FormattableString instances. This is a very useful feature in combination with safe SQL queries and the SqlQuery method of Entity Framework Core.

Read the whole article

Preview image blogpost

async2 - The .NET Runtime Async experiment concludes

The .NET team has been working on a new experiment called async2, which is a new implementation of the async/await pattern that is designed to be more efficient and more flexible than the current implementation. It started with green threads and ended with an experiment that moves async and await to the runtime. This post will cover the journey of async2 and the conclusion of the experiment.

Read the whole article

Preview image blogpost

Organizing Parameters in Minimal API with the AsParametersAttribute

Even though it was introduced in .NET 7, I came across recently the AsParametersAttribute. Let's have a look what it is good for.

Read the whole article

Preview image blogpost

The state machine in C# with async/await

You often here that the async/await keywords leads to a state machine. But what does that mean? Let's discuss this with a simple example.

Read the whole article

Preview image blogpost

How not to benchmark!

I came across a recent LinkedIn post about the let statement in LINQ and it's performance implication. And in typically influencer fashion it out right claimed that using let in LINQ is a bad idea and should be avoided. But is it a bad idea?

Read the whole article

Preview image blogpost

Codespaces for your open-source project

In this blog post, I will show you how to use GitHub Codespaces to make it easier for contributors to get started on your open-source project. We will set up a codespace for a .NET repository and configure it to install the required dependencies and tools.

Read the whole article

Preview image blogpost

ReadOnlySet<T> in .NET 9

The next preview (preview 6) will bring a new type ReadOnlySet<T>. This is a read-only set that is similar to ReadOnlyCollection<T>. Let's see how it works and why it was introduced.

Read the whole article

Preview image blogpost

NCronJob - June Edition

The last update of NCronJob was some time ago - and as always, there are some new features in the meantime. So here we are, let's go through to highlight them!

Read the whole article

Preview image blogpost

Are my EF LINQ to SQL queries safe?

Have you ever asked yourself if your EF LINQ queries are susceptible to SQL injection attacks? Either because you are querying some user data from a text field or directly taking whatever your API hits against the database?

Read the whole article

Preview image blogpost

Does an HttpClient await the Header and the body?

If you call HttpClient.GetAsync or HttpClient.PostAsync and then await the result, does the await wait only for the headers to be received or does it wait for the body to be received? Let's find out!

Read the whole article

StringBuilders magic for very large strings

The StringBuilder class is used to create mutable sequences of characters. Strings are immutable, so if you need to perform multiple operations on a string, it is better to use a StringBuilder instead of a string. This is especially useful when you need to concatenate a large number of strings. But there is more magic to it, especially when we go BIG!

Read the whole article

Preview image blogpost

Cancel WhenAny - linked CancellationTokenSource

In today's short post, I will show you how to cancel a Task with multiple inputs (aka multiple CancellationTokens) using CancellationTokenSource and CancellationTokenSource.CreateLinkedTokenSource.

Read the whole article

Preview image blogpost

Help my memory dump always shows me some exceptions!

I made a memory dump in my simplest console application and there are a bunch of exception instances around, what is going on? Let’s see in this blog post, why you see a few exception instances in your memory dump.

Read the whole article

Preview image blogpost

MemoryCache, DistributedCache and HybridCache

The latest preview (.NET 9 preview 4) brought another caching structure to the .NET world - so let's order some things here.

Read the whole article

Preview image blogpost

Generate http files from a swagger definition

Http files are nice and handy - but they are also a bit of a pain to update. So why not generate them from a swagger definition?

Read the whole article

Preview image blogpost

NCronJob - Big Updates

Since the last blog post a lot has happened and many new features have been added to NCronJob. In this blog post I would like to introduce you to the new features and explain how you can use them.

Read the whole article

Preview image blogpost

.NET 9 LINQ Performance Edition

As with almost every edition of .NET, the team has been working on improving performance. In this blog post, we will see some improvements to the related tickets and benchmarks.

Read the whole article

Preview image blogpost

How does a List know that you changed it while enumerating it?

Everyone falls for that and tries to change a list while enumerating it greeted by the System.InvalidOperationException: Collection was modified; enumeration operation may not execute. message. But how does the List know that you changed it? Let's find out.

Read the whole article

Preview image blogpost

Does readonly make your code faster?

In this blog post we will discover whether or not the readonly modifier can make your code faster. So without further ado let's get started.

Read the whole article

Preview image blogpost

Fluent API to await multiple calls and get their respective results

Sometimes, you have multiple async calls to make, and you want to do that asynchronously and get the results afterward. Let's build a fluent API to do that.

Read the whole article

Preview image blogpost

Equip 3rd party types with a deconstructor

Deconstructor are a C# language feature that allows you to define a method that will be called when an object is being split up into its components. While this is straightforward to implement for your own types, it is not possible to add a deconstructor to a 3rd party type - or is it?

Read the whole article

Preview image blogpost

Pattern matching and the compiler can be surprising

Pattern matching is a powerful feature in C#. It allows you to match a value against a pattern and extract information from the value. The compiler does the magic for you - and sometimes it struckles with that.

Read the whole article

Preview image blogpost

C# 13: Allow ref and unsafe in iterators and async

C# 13 might get a new feature soon that allows ref and unsafe in iterators and async methods.

Read the whole article

Preview image blogpost

NCronJob - Scheduling made easy

Hangfire/Quartz or BackgroundService? Why not something in the middle? Did you ask yourself this question from time to time? Do you want to have a full-blown job scheduler with lots of setups, but more than BackgroundService is needed?

Meet: NCronJob!

Read the whole article

Preview image blogpost

bUnit v2 - The Blazor unit testing library vNext

Next to the big release of .NET 8, we also released the first preview bUnit v2. This release is a major release, with a lot of new features and improvements. In this post, I will highlight some of the most important changes. This includes new features but also some breaking changes.

Read the whole article

Preview image blogpost

Typesafety in xUnit with TheoryData<T>

I recently discovered this small but very useful utility in xUnit: TheoryData<T>.

Read the whole article

Preview image blogpost

Avoid multiple boolean parameters

Boolean parameters are nice, but it's hard to keep track of what each one does when you have multiple of them. In this blog post, we will see why it's better to avoid multiple boolean parameters and how to refactor them.

Read the whole article

Preview image blogpost

SearchValues object become better with .NET 9

SearchValues, which were introduced with .NET 8 will become an upgrade and becomes more usable! Let's see how.

Read the whole article

Preview image blogpost

Three new LINQ methods in .NET 9

Even though we are in the alpha of .NET 9 and .NET 8 was released not more than two months ago, the dotnet team does not sleep and pushes new changes! In this blog post, we are checking what new methods were added to everyones favorite: LINQ.

Read the whole article

Preview image blogpost

An alternative to AutoMapper

I am not the biggest fan of AutoMapper. It starts with good intentions but often ends up being a big mess. I have seen it used in many projects, and the configuration of the mappings is often scattered all over the place, and or they are huge!

Read the whole article

Preview image blogpost

Const strings are not so const after all

We know the const keyword with strings - but are they really constant after all? Or can we use some tricks to modify them? Let's see.

Read the whole article

Preview image blogpost

An asynchronous lock free ring buffer for logging

In this blog post, I showcase a very simple lock-free ring buffer for logging. I'll show why it's useful and how it works.

Read the whole article

Preview image blogpost

The first possible new feature of C# 13: Params collection

Only one month after the big release of .NET 8, the dotnet team is already working on the next iteration: .NET 9. With that also comes new language features. The first one is about to be merged into the main development branch: Params Collections.

Read the whole article

Preview image blogpost

Entity Framework - Storing complex objects as JSON

From time to time, it is nice to store complex objects or lists as JSON in the database. With Entity Framework 8, this is now easily possible. But this was possible all along with Entity Framework 7.

Read the whole article

Preview image blogpost

Blazor .NET 8 - Enhanced Form Navigation

There are many new cool features with .NET 8 and Blazor in particular. In this blog post, I want to highlight a feature that I believe is very useful in the new context Blazor is living.

Read the whole article

Preview image blogpost

A more flexible and enhanced way of logging in .NET 8

The latest version of the .NET (version 8) has introduced a "better" way of logging. This new way of logging is more flexible and enhanced than the previous versions. It is about the LoggerMessageAttribute.

Read the whole article

Preview image blogpost

Interactive LINQ tutorial, especially for beginners

LINQ (Language Integrated Query) is a powerful feature of C# that allows you to query data from different data sources. It is a must-have skill for every C# developer. That is why I created: https://linqmarbles.info/

Read the whole article

Preview image blogpost

Redux Pattern in Blazor

In this blog post, we will use the Redux pattern with a small Blazor application. To demonstrate the inner workings, we will built everything from scratch.

Read the whole article

Preview image blogpost

Yes you can create classes on the stack!

In this article we will create a class, aka a reference type on the stack, and therefore don't use any managed memory!

Read the whole article

Preview image blogpost

Interfaces can have private methods

Let's drop some "useless" knowledge here. Interfaces can have private methods. This comes with the C# 8 feature: "Default interface methods".

Read the whole article

Preview image blogpost

Structured Concurrency in C#

Did you ever hear about "Structured Concurrency"? If not, this article is for you. We will discover what it is, why it is useful, and what it could look like in C#.

Read the whole article

Preview image blogpost

.NET 8 and Blazor United / Server-side rendering

New .NET and new Blazor features. In this blog post, I want to highlight the new features that are hitting us with .NET 8 in the Blazor world. So let's see what's new.

Read the whole article

Preview image blogpost

Questions I asked as .NET interviewer

This blog post is a small collection of questions I asked as a technical interviewer when we had candidates for software developer positions. This might be helpful for you if you are preparing for a job interview.

Read the whole article

Preview image blogpost

Less boilerplate code with the new primary constructor in C# 12

The new language feature "primary constructor" which will be released with C# 12 / .NET 8 this year (November 2023) allows you to remove some ceremonial code. Let's see how.

Read the whole article

Preview image blogpost

A new way of doing reflection with .NET 8

.NET 8 introduced a new way of doing reflection. Why did they introduce this, and what are some benefits - this blog post will give you some insights.

Read the whole article

Preview image blogpost

Building a Minimal ASP.NET Core clone

In this article, we will build a minimal version of what ASP.NET Core does - yes, you read right. We will create a very simplistic clone of ASP.NET Core to discuss how the whole thing works. Beginning with a simple console application, we will add the necessary components to make it work as a web server. Bonus points for our own middleware pipeline and dependency injection.

Read the whole article

Preview image blogpost

Enabling List<T> to store large amounts of elements

List<T> is one of the most versatile collection types in .NET. As it is meant for general-purpose use, it is not optimized for any specific use case. So, if we look closely enough, we will find scenarios where it falls short. One of these scenarios is when you have lots of data. This article will look at precisely this.

Read the whole article

Preview image blogpost

Turn on Nullability checks by default

Since C# 8, we have nullable reference types. The word sounds odd, given the fact that reference types are always nullable. The idea is that the default is that your reference types have to be properly initialized. Here are my thoughts after a few years of using them.

Read the whole article

Preview image blogpost

The "Weak Event" Pattern in C#

Events in C# are a powerful mechanism for decoupling components and enabling a publisher/subscriber model. However, they have a significant drawback: the publisher holds a strong reference to the subscriber, and this can cause memory leaks. This article describes a pattern for implementing weak events in C#.

Read the whole article

Preview image blogpost

Expression-bodied members in properties

Are these two expressions the same?

public class MyClass
{
    public int A { get; } = Random.Shared.Next(1000);
    public int B => Random.Shared.Next(1000);
}

Read the whole article

Preview image blogpost

Enum.TryParse unexpected behavior

Enums are very simple structures, but some functions like Enum.TryParse can have unexpected behavior. In this short blog post, we discover why and what are the alternatives.

Read the whole article

Preview image blogpost

Creating Your Own Fakes Instead of Using Mocking Libraries

With respect to the current topic around Moq, I want to showcase how you can easily roll out your own fakes so that you are not depending on a third party library.¨

Read the whole article

Preview image blogpost

What's going on with Moq? SponsorLink and burnt soil!

The famous Moq library faced some criticism due to the usage of SponsorLink. What is the problem, and what is going on here? And obviously, I will add all the sources to the articles.

Read the whole article

Preview image blogpost

Keyed Services in the IServiceProvider in .NET 8 preview 7

The .NET 8 preview 7 will bring another exciting feature some of you probably awaiting for a long time: Keyed services.

Read the whole article

Preview image blogpost

The combined power of F# and C#

Where C# is the most dominant language in the .NET world, other languages are built on top of the Framework that deserves their respective place. F# is strong when it comes down to functional programming! In this blog post, we will leverage the power of F# and C# to showcase where both excel!

Read the whole article

Preview image blogpost

Gracefully Handling Entity Framework Exceptions with EntityFramework.Exceptions

Working with databases can sometimes be daunting, mainly when errors occur. These errors or exceptions can be due to many reasons, such as constraint violations, connection issues, or syntax errors. Entity Framework throws a generic DbException or DbUpdateException for most of these database issues. But we cand get more specific exceptions based on the concrete "problem"! That's where EntityFramework.Exceptions comes in.

Read the whole article

Preview image blogpost

.NET Framework 4.8 to .NET 6 migration

I was recently tasked to migrate an application with around 150 projects from the "old"It is still supported .NET Framework 4.8 to a recent .NET 6. As the application is still under development and used, the migration should be done step by step over time in iterative steps rather than a big bang refactoring. This blog post will go a bit into more detail about how I approached the situation and what I learned.

This is a highly subjective post, and there are plenty of ways of approaching it - so take it with a grain of salt and mileage may vary.

Read the whole article

Preview image blogpost

Three tricks with Dictionary

In this short blog post, I want to showcase three nice tricks you can do with everybody's favorite data type: the dictionary.

It is a versatile data structure, and we can make it even more versatile!

Read the whole article

Preview image blogpost

Overload resolution in C#

On a recent LinkedIn Post from Saeed Esmaeelinejad, he asked what is the outcome of:

bool flag = SomeMethod();

M(flag ? 1 : 2);

void M(long number) => Console.WriteLine("long");
void M(short number) => Console.WriteLine("short");

What is the outcome?

Read the whole article

Preview image blogpost

Why I like and prefer xUnit

In almost all of my projects, I only use xUnit, and here is a small love letter. Especially the one fact I do think makes it a good choice!

Read the whole article

Preview image blogpost

LINQ: Select.Where or Where.Select?

LINQ is a very powerful tool for querying data. As the majority of functions are built on top of IEnumerable<T> and it, in most cases returns IEnumerable<T> as well, it is very easy to chain multiple functions together. That leaves you with a question: which one should I use, Select.Where or Where.Select?

Read the whole article

Preview image blogpost

Missing Stack trace when eliding the await keyword

You may have heard that when you elide the await keyword in a method that returns a Task or Task<T>, you lose the stack trace. Buy why does that happen? Let's find out!

Read the whole article

Preview image blogpost

Create your own Mediator (like Mediatr)

In this blog post, I'll show you the fundamentals of the Mediator pattern and how to implement it in your application from scratch. And yes, we basically implement the famous MediatR library.

Read the whole article

Preview image blogpost

C# 12: Collection literals

A new feature is hitting C# 12 and it is called Collection literals. In this blog post, I will show you what it is and how it works.

Read the whole article

Preview image blogpost

How does List work under the hood in .NET?

A List is one of the most used data types in .NET. You can dynamically add elements without taking care of how that happens. But do you know what is going on under the hood?

Read the whole article

Preview image blogpost

Span / Memory / ReadOnlySequence in C#

There are many different memory types used in modern C# programs. The more common ones are Span<T> and Memory<T>. Occasionally there is also ReadOnlySequence<T>. What do these types do?

Read the whole article

Preview image blogpost

Time abstraction in .NET 8

With the upcoming release of .NET, the team introduced an abstraction of time itself. That can bring you major benefits especially if you have to test scenarios where time is a crucial part! Until now, you had to create your own wrapper. This, of course, makes integration with 3rd party libraries tricky.

Read the whole article

Preview image blogpost

nameof get's a bit better in C# 12

The nameof operator is a great way to get the name of a variable, type, or member. With C# 12 it's getting even better. Let's see how.

Read the whole article

Preview image blogpost

How does TryGetNonEnumeratedCount work?

TryGetNonEnumeratedCount attempts to determine the number of elements in a sequence without forcing an enumeration. It returns true if it could and false if it couldn't. The API was added with .NET 6 - let's have a look at how that thing works.

Read the whole article

Preview image blogpost

6 useful extensions for IEnumerable

I did already write about some useful extension methods for Task and ValueTask. Today I want to show you some useful extension methods for IEnumerable.

Read the whole article

Preview image blogpost

Some cool things you can do with ValueTuple

In this blog post, we will explore some cool things you can do with ValueTuple. Also, a short explanation of what ValueTuple is and how it works.

Read the whole article

Preview image blogpost

Entity Framework and ordered indexes

In Entity Framework 7, the team has added support for ordered indexes to the fluent API. In this blog post we will look at how to use this feature and what it means for your database.

Read the whole article

Preview image blogpost

Controlling the log level of your application

In this blog post, we will have a look at the different log levels and how to control them.

Read the whole article

Preview image blogpost

Verifying your DI Container

Microsoft's integrated dependency injection (short DI) container is very powerful, but there are also certain pitfalls. In this article, I will show you what some of the pitfalls are and how you can verify them.

Read the whole article

Preview image blogpost

Create your own Validationattribute in ASP.NET Core

In this small blog post, I will show you how to create your own Validation attribute in ASP.NET Core to tailor-made your validation rules.

Read the whole article

Preview image blogpost

Domain events and the "Unit of Work" pattern

In this blog post, we will discuss the "Unit of Work" pattern and how it can be used to implement domain events in a DDD application. For that, we will also discuss how we can leverage middleware to implement the "Unit of Work" pattern in a .NET application. A lot of things are going to happen in this blog post, so let's get started.

Read the whole article

Preview image blogpost

Covariance and Contravariance in C#

Let's talk about Contravariance and Covariance in C# using .NET Framework examples!

Contravariance and covariance are essential concepts in C# when dealing with generics, enabling us to have more flexibility when assigning generic types. So let's have examples straight from the framework itself!

Also, we will go a bit deeper and talk what some differences between generic constraints and things like Contravariance are.

Read the whole article

Preview image blogpost

.NET 8 Performance Edition

As with every .NET release, Microsoft improves the performance of the runtime and guess what: This release is no exception to this. In this blog post, I want to go through some of the improvements made so far (.NET 8 preview 3).

Read the whole article

Preview image blogpost

5 useful extensions for Task<T> in .NET

In this short blog post, I will show you 5 useful extensions for Task in .NET. We will build them as extension methods, so there are easy to use. On top, I will show a small example of how to use them. So let's go!

Read the whole article

Preview image blogpost

Source Generators and Regular Expressions

Source Generators are more and more an integral part of the .NET ecosystem. But how does that play together with everyone's favorite: Regular Expressions?

In this blog post we will dive in how we can leverage source generators in combination with regular expression to have a debuggable, but also very performant way of executing regular expressions!

Read the whole article

Preview image blogpost

LINQ on steroids with SIMD

In this blog post, we will explore the use of SIMD instructions to speed up LINQ queries. We will use the Vector type of performing SIMD operations on arrays of data. We will also use the BenchmarkDotNet library to measure the performance of our code. We will also see how this works hand in hand with the new "generic math" feature of C# 10.

Read the whole article

Preview image blogpost

Creating a ToolTip Component in Blazor

In this blog post we will create a ToolTip component in Blazor from scratch. We will use the Blazor WebAssembly template to create a new project. We will then add a ToolTip component to the project and use it in the Index page. We will also add some styling to the ToolTip component.

The advantage over using a library is that we can customize the component to our needs as well as keeping it simple! So let's get started!

Read the whole article

Preview image blogpost

C# Source Generators: How to get build information?

Source generators are a powerful feature introduced to C#, allowing developers to generate additional code during the compilation process automatically. They can help reduce boilerplate, improve performance, and simplify your codebase.

This blog post will introduce source generators, discuss how they work, and walk through an example of a source generator for generating build information.

Read the whole article

Preview image blogpost

Leverage 'is not' Operator for Exception Filtering!

Did you know you can use the 'is not' operator with exception filtering to simplify and improve your error handling in C#?

In this short blog post, I will show you how to use it.

Read the whole article

Preview image blogpost

Caching in .NET with MemoryCache

In this blog post, we will discuss how we can "cache" entries from the database. We will talk about why we would do this in the first place and how to achieve that.

Also, we will talk about some implications and what "cache invalidation" is.

Read the whole article

Preview image blogpost

Write your own AutoMapper in C#

Sometimes you have to map an object to another representation in C#. And you think: Why isn't C# duck-typing capable?

You might hear of libraries like AutoMapper that do the tedious work of mapping one object to another with the same structure. This blog post will give a super simple introduction to how those libraries are working internally.

In the end a bit of a subjective topic on whether or not I would use such libraries.

Read the whole article

Preview image blogpost

LINQ // Skip and Take

Skip and Take are used for pagination or limit the number of elements returned by a query.

Since C# 8 you can use Take with a Range. Let's see some examples.

Read the whole article

How to write your own cron Job scheduler in ASP.NET Core (like Quartz, Hangfire, ...)

In this blog post we will discover how to write your own small task scheduler / job scheduler with cron notation in ASP.NET Core. You might know similar approaches under the name of Quartz or Hangfire.

With the help of BackgroundService we will build our own, lightweight version of it.

Read the whole article

Preview image blogpost

Benchmarking - A matter of perspective

In recent months and years, there was a certain hype around benchmarking, also in the .NET community.

This blog post is meant to ground some of the benchmarking topics and put this into relation to other things so you get a better understanding if it's worth the effort.

Read the whole article

Preview image blogpost

Is a square a rectangle? Liskov substitution principle in action

I will put that simple question in the room: "Is a square a rectangle?" And you might thank: "Well dah, of course!"

But wait for a second and let's check it together. We will use the L in SOLID: The Liskov Substitution principle to check if this relationship makes sense for us!

Read the whole article

Preview image blogpost

The Humble Object Pattern

The Humble Object Pattern is a design pattern to make especially unit testing easier with the goal of separating behaviors that are easy to handle (domain logic) from behaviors that are hard to handle (like external events or dependencies).

So let's have a look at what it is and how you can utilize it.

Read the whole article

Preview image blogpost

Performance (ReadOnly)List vs Immutable collection types

A bit back on LinkedIn, there was a discussion about read-only collection and immutability where this is not the point I want to discuss now, as I already covered that here: "ReadOnlyCollection is not an immutable collection".

This post is just about the performance of those types compared to our baseline, the good old List<T>. It also explains why we see the results we see.

Read the whole article

Preview image blogpost

From Testing Pyramid to Diamond

In this article, we will discuss the testing pyramid - what it is and what are some problems with that.

We will also discuss a different approach: The testing diamond.

Read the whole article

Preview image blogpost

Getting git version information in your C# code

Did you ever need git-specific information like the latest tag or the current commit inside your C# code? Or even the semantic version number of your current build=

Well, there is an easy solution involving source generators.

Read the whole article

Preview image blogpost

A (performance) quirk with JsonSerializer

System.Text.Json.JsonSerializer has a weird quirk in regard to performance and memory management. So we will discuss what is "wrong" with this code: JsonSerializer.Serialize(myObject, new JsonSerializerOptions(...));.

Read the whole article

Preview image blogpost

What is a Middleware and how to use it in ASP.NET Core?

Did you ever ask yourself: What is a middleware, and why should I use it?

If so, this blog post is exactly for you. We will see where we could use a middleware and also how we can use the Dependecy Injection container of ASP.NET Core.

Read the whole article

Preview image blogpost

Multi-Tenancy with RavenDB and ASP.NET Core

Multi-tenancy is a software architecture pattern where a single instance of a software application is used by multiple customers, with each customer having separate and isolated data, configurations, and resources. RavenDB is a NoSQL document database that provides a flexible and scalable solution for multi-tenant applications. This blog post will explore why multi-tenancy exists, the advantages of using RavenDB for multi-tenant applications, and provide code examples to get you started.

Read the whole article

Preview image blogpost

C# Language Mind map

This blog post contains a mind map of language features starting from C# 1 up til now - including some of the new C# 12 features that will be released in November 2023.

Read the whole article

Preview image blogpost

Repository Pattern - A controversy explained

In this blog post, we'll dive into the ins and outs of the repository pattern and examine both its benefits and its potential drawbacks. We will start from the very basic to some more advanced use cases. So let's dive right into it.

Read the whole article

Preview image blogpost

Native DateOnly and TimeOnly support in Entity Framework 8 in SQL Server

.NET 6 brought us two new datatypes: DateOnly and TimeOnly. For those types we don't have any first class support in Entity Framework - until now.

There is a recent change, that hit us with Entity Framework 8 that might ease the situation and brings native support for those types.

Read the whole article

Preview image blogpost

C# Lowering

Did you ever hear the word "compiler magic" or "syntactic sugar"? Probably yes and therefore we want to dissect what this "magic" really is!

We can see how we can predict performance or bugs by "lowering" our code. Also we will see how things like foreach, var, lock, using, async, await, yield, anonymous types, record, stackalloc, pattern matching, Blazor components, deconstructor, extension methods... do not really exist.

Read the whole article

Preview image blogpost

Deep nesting - Why and how to avoid

... if you need more than 3 levels of indentation, you're screwed anyway, and should fix your program.

This is written in the Linux style guide. Let's see why they have that rule and how we can overcome deeply nested code.

Read the whole article

Preview image blogpost

C# 12: Primary Constructors

Another new C# 12 feature might drop soon and makes its debut with the next iteration: Primary Constructors.

The blog post will talk about what a Primary constructor is, why we already have it, and what the proposal tries to change. Exciting times are ahead of us!

Read the whole article

Preview image blogpost

Cohesion - An indicator for refactoring

Cohesion represents the degree to which the elements of a module belong together. A module or class is said to be highly cohesive if its methods and data are highly related, meaning that a change in one affects just a small number of elements.

We can use this metric to know whether or not an object is in a good shape or needs some refactoring.

Read the whole article

Preview image blogpost

Entity Framework 8: Raw SQL queries on unmapped types

The next iteration of Entity Framework, namely Entity Framework 8, will have a new and exciting feature:

Support raw SQL queries without defining an entity type for the result

That means less boilerplate code!

Read the whole article

Preview image blogpost

Easy Pagination for Entity Framework in 3 steps

Pagination is the process of dividing a set into discrete pages. In the context of Entity Framework, that means we are only getting a certain amount of entries from the database.

And we will implement a very easy solution to make that happen in 3 steps. The result will look like this:

var pagedList = DbContext.BlogPosts.ToPagedList(page: 1, pageSize: 5);

Read the whole article

Preview image blogpost

No, No, No - Tasks are not threads and they are not for performance!

I often read that Task is used for multithreading in C# / .NET, but that is not the case. And it is crucial to understand why this isn't the case. We will also see which problem exactly Task is solving in the first place.

Read the whole article

Preview image blogpost

.NET Tips and Tricks & ValueStringBuilder

I want to showcase two of my many side projects. My .NET Tips and Tricks website, where I collect and categorize, well, tips and tricks around .NET-related topics as well as my ValueStringBuilder.

Read the whole article

Preview image blogpost

Give your strings context with StringSyntaxAttribute

Strings are one of the most universal data types. We use them for URLs or regular expressions or even to define some date. With .NET 7 we have a new way of giving those strings a bit of meaning. Meet StringSyntaxAttribute.

I also show you a way how to use them in .NET 6 and earlier.

Read the whole article

Preview image blogpost

C# 12: Default Parameters in Lambdas

There is still a long road ahead of us until the release of .NET 8, but the first new language constructs are getting public. The first one I want to present is: Default Parameters in Lambdas.

Read the whole article

Preview image blogpost

ReadOnlySpan<char> and strings - How not to compare them

Many know that you can take ReadOnlySpan<char> objects when dealing with strings. They give you a direct way of operating on the underlying memory. Often times you can use them interchangeably, but there are scenarios where you really have to watch out what is going on.

This blog post will have a look at a major problem with ReadOnlySpan when used like a "regular" string.

Read the whole article

Preview image blogpost

Structure and order your DI container

Does your Dependency Injection container is one big pile of method calls one after the other? Are there 50 lines of just AddScoped, AddTransient, and so on? Well, let's fix this.

We can utilize extension methods to make an order to that mess!

Read the whole article

Preview image blogpost

Array, List, Collection, Set, ReadOnlyList - what? A comprehensive and exhaustive list of collection-like types

.NET knows a big list of collection-like types like: IEnumerable, IQueryable, IList, ICollection, Array, ISet, ImmutableArray, ReadOnlyCollection, ReadOnlyList, and many more.

This blog post will give you an exhaustive list of types in .NET and when to use what.

Read the whole article

Preview image blogpost

Simple DI - Container

This blog post will show you a very simple Dependency Injection container.

This will give a better understanding of what Dependency Injection is and how it is done. And sure we will see how this is related to IoC - Inversion of Control.

Read the whole article

Preview image blogpost

Delete a record without prior loading in Entity Framework

Sometimes you have an Id of an object and want to delete the underlying thing from the database. But it doesn't make sense to load the whole object from the database to memory first. So how can we achieve this quickly?

Read the whole article

Preview image blogpost

ChatGPT - Current state for .NET - and in general

ChatGPT is going viral right now. Besides funny conversations, you can use that tool to generate also code for you. But does it really hold up to its reputation and it is a serious pairing partner? Let's see.

Read the whole article

Preview image blogpost

Check for elevated rights in .NET 8

In the past, it was tricky to get if the current process runs under elevated rights. In the sense of it is run under the sudo group in *nix (Unix, Linux, macOS, you name it) or administrative rights in Windows.

But that changes with .NET 8 as we now have a unified API for that.

Read the whole article

Preview image blogpost

Abstraction vs Encapsulation

Abstraction and Encapsulation are two fundamental concepts in object-oriented programming. So let us have a small look what the difference is between those two.

Read the whole article

Preview image blogpost

How to enumerate through a StringBuilder

Did you ever wonder how we can iterate through a StringBuilder? I mean, of course, we can just call ToString and use the returned string, but that means we materialize the whole thing without good reason.

We can also use a normal for-loop. But we can also find a completely different and probably dumber way! And if you wonder: No, this is not something you do in your daily life, but by doing so, I can show some cool stuff C# and .NET offer.

Read the whole article

Preview image blogpost

New ArgumentException and ArgumentOutOfRangeException helpers in .NET 8

Do you remember how .NET 6 introduced the ArgumentNullException.ThrowIfNull guard? And afterward, with .NET 7 we've got this excellent bit: ArgumentException.ThrowIfNullOrEmpty? Guess what, there might come some new handy additions for the upcoming .NET 8 iteration.

So let's see what are those new changes and how they make the code simpler.

Read the whole article

Preview image blogpost

A new wave of analyzers in .NET 8

Analyzers did become an integral part of the .NET ecosystem. Their main responsibility is to find potential code issues and warn you. Often times this comes even with potential fixes you can directly apply.

And Microsoft will continue this journey with the upcoming .NET 8 release. This blog post will show you potential candidates, which will make the cut.

Read the whole article

Preview image blogpost

Frozen collections in .NET 8

.NET 7 was freshly released but Microsoft does not sleep. .NET 8 is already in the making and I want to showcase to you one new area where the dotnet team is working on Frozen collections.

So let's have a look at what frozen collections are and how they are working.

Read the whole article

Preview image blogpost

"Use always a StringBuilder" - Internet myths

Use always a StringBuilder

That is what you can read from time to time. The basic idea is, that a StringBuilder is "better" to be defined.

Why are people telling that lie? Let's discuss this and see what it isn't true.

Read the whole article

Preview image blogpost

How to get allocations in .NET? And how big is an empty array?

Often times we hear about allocations on the heap. How can we easily measure this? This article will show you a very easy way of doing so.

Plus we will answer the question how big is an empty array? And if you think 0 bytes, then spoiler alert, that is not the case at all.

Read the whole article

Preview image blogpost

Anonymous test data with AutoFixture

Often times we have unit or integration tests that rely on some input data. The easiest solution is just to take some hard-coded values and move on with life. This has some major downsides:

Giving specific values in a test carries meaning, but we are often times not interested in that. We just need to pass the object around to fulfill the API. Also the simplest solution to fulfill your test is literally checking against those values.

Here is an elegant solution to that problem: AutoFixture. I will show you what it can do, especially in combination with xUnit.

Read the whole article

Preview image blogpost

Mutable value types are evil! Sort of...

You might have heard that mutable value types are evil. But why is that and why does the .NET framework use them then? Are they really that evil?

Let's have a look at a few examples and have a look what is going on!

Read the whole article

Preview image blogpost

Marking API's as obsolete or as experimental

Often times your API in your program or library evolves. So you will need a mechanism of telling that a specific API (an interface or just a simple method call) is obsolete and might be not there anymore in the next major version.

Also it can happen that you have a preview version of a API, which might not be rock-stable and the API-surface might change. How do we indicate that to the user?

Read the whole article

Preview image blogpost

Infographics Compendium III - Exceptions, EF Sanitized, Operators, ...

This edition has the following infographics:

  • DebuggerDisplayAttribute
  • Entity Framework input and LINQ - is it safe?
  • ExceptionDispatchInfo
  • implicit and explicit operator

Read the whole article

Preview image blogpost

local functions vs lambda expressions

.NET knows local functions and lambda expressions. You can almost take them interchangeably, but there are also some differences between them.

This article will show the differences between them.

Read the whole article

Preview image blogpost

Throwing exceptions - Why is my stack trace lost?

You might have read, that re-throwing an exception like this: throw exc; is considered bad practice and you should just do this: throw; instead.

But why is it like that?

Read the whole article

Preview image blogpost

LiteDB - A .NET embedded NoSQL database

In this article we will have a closer look at LiteDB, a .NET NoSQL Document Store in a single data file. We will discover the advantages of LiteDB and why it is a viable candidate for your next project.

We will also explore what are the differences between a NoSQL and a classical SQL database are and what this has to do with the reminiscent SQL CE or the more modern SQLite database.

Read the whole article

Preview image blogpost

Cursed C# - Doing shenanigans in C#

In this short blog post I want to show you two silly things so that you can apply right now! Both of them equally silly, but that is not the point (is it ever?).

We will see how to await an integer or TimeSpan and how to foreach through an integer. All of this thanks to the magic of extensions methods.

Read the whole article

Preview image blogpost

Infographics Compendium II - ThrowHelper, null Task and more

This edition has the following infographics:

  • ConfigureAwait on IAsyncDisposable
  • Index in foreach
  • Non-destructive mutations with struct
  • Returning null for a Task
  • Throw-Helper
  • verbatim strings

Read the whole article

Preview image blogpost

Low-level struct improvements in C# 11

C# 11 brings some major improvements for structs. You remember Span<T>, which you couldn't create?

Now you can. C# 11 allows ref fields in a struct. Why this is a cool thing and what you can do with it, you will see in a minute.

Read the whole article

Preview image blogpost

Introduction to WebApplicationFactory

This article will show you what exactly a WebApplicationFactory is and why it is so "mighty" when it comes down to testing. I will highlight some of the properties, which you can leverage to write powerful tests.

Read the whole article

Preview image blogpost

Infographics Compendium I - Generators, pure functions and more

Sometimes I publish parts of my infographics I publish on various channels with more explanation.

And then sometimes I don't. This time I just put some of my (hopefully self-explanatory) infographics here.

  • Pure functions
  • Generator functions
  • Cost of anonymous types

Read the whole article

Preview image blogpost

x86 vs x64 in .NET

In this article I will show you what is the difference between x86 (32-bit) vs x64 (64-bit) in the .NET World.

What is the impact if you choose on or another.

Read the whole article

Preview image blogpost

Pattern matching is awesome

Pattern matching, which was introduced in C# 9, is a hell of a beast and does more than you might think.

In this small blog post I show you where the magic is and what it does under the hood.

Read the whole article

Preview image blogpost

Blazor Project Structure

Did you ever wonder what is a nice way of structuring your Blazor application?

I will show you how I structure my Blazor projects (as well as this very blog). What are the upside in contrast to the "default" structuring you get with the Blazor template.

Read the whole article

Preview image blogpost

Memory is complicated

This is a small story about how memory operates in your .NET application. Well not only .NET but how memory does or does not get allocated.

We will see how a 1 Gigabyte big array is only a few megabytes big to some extend. Furthermore I will discuss working set and committed memory.

Read the whole article

Preview image blogpost

ASP.NET Core - Why async await is useful

Did you ever wonder why you "should" use async and await in your ASP.NET Core applications? Most probably, you heard something about performance. And there is some truth to it, but not in the way you might think.

So let's discuss this with smaller examples.

Read the whole article

Preview image blogpost

LINQ explained with sketches - the eBook

After covering and collecting multiple parts of LINQ explained with sketches I bundled them all together in a small booklet with more explanation and code samples.

Therefore I present: LINQ explained with sketches - the eBook. Over 30 pages with smaller explanations and more LINQ operations than in my last post. Litte Bonus: There are interactive links with smaller examples to fiddle around with.

Read the whole article

Preview image blogpost

EF7 - Bulk updates and Bulk deletes

Finally the long awaited bulk update and bulk delete feature is heading towards Entity Framework 7. So we will have a look how to use it and what might be some limitations.

Also I will have a quick look at the performance aspect, because this was the main driver for that feature.

Read the whole article

Preview image blogpost

NDepend

NDepend is a static analysis tool for .NET managed code. The tool proposes a large number features, from dependency visualization to Quality Gates and Smart Technical Debt Estimation. For that reasons the community refers to it as the "Swiss Army Knife" for .NET Developers.

So let's check if that descriptionI shamelessly stole from Wikipedia checks out and what we can do with that tool.

Read the whole article

Preview image blogpost

LINQ explained with sketches

Often times it is easier to have a nice illustration at hand, which explains you things the easy way. So let's do this for a lot of LINQ operations like Where, Select and friends.

Of course a small explanation will be attached as well.

Read the whole article

Preview image blogpost

Mediator Pattern - CQRS with MediatR

The famous mediator pattern. Used so often especially in combination with CQRS.

If you know how to order food at a restaurant then you already halfway there to understand how the CQRS pattern works. I promised it is not that difficult 😉

In this article I will show how the mediator pattern itself works, what CQRS is and its advantages. For that we will write a small application, which demonstrates how to use the pattern and what we gain from using it.

Read the whole article

Preview image blogpost

Logging Source Code Generators

Since .NET6 we have the possibility to define an easy way of logging common statements:

Meet Compile-time logging source generators. This article will show why we have them and how to use them. Of course a smaller benchmark will also follow.

Read the whole article

Preview image blogpost

Blazor Client - Loading Screen

If you are using Blazor WebAssembly aka client-side Blazor you are faced with an issue: The .NET runtime including your assemblies has to be downloaded first. We are taking about some megabytes as the initial load.

Depending on the connection of your client there is a time where basically nothing happens. The default template just has a simple "Loading..." text. So let's change that.

Read the whole article

Preview image blogpost

Abstract class vs interface

In C# we have abstract classes and we also have interfaces. Both seem very similiar but they are fundamentally different concepts.

Therefore let's discover what the difference is, what the overlap is and when to use what.

Read the whole article

Preview image blogpost

SOLID Principles in C#

SOLID principles is one of those words/phrases you hear so often about. Also one of those things you most often get asked by your recruiter in a technical assessment.

So let us dissect why Uncle Bob formulated them and how they contribute to "Clean Code".

Read the whole article

Preview image blogpost
  • 6/30/2022
  • 4 minute read

C# vNext - What could come

C# 11 is in front of our doorsteps. A lot of the features are know, so let us have a look at the future. We will discover some features which could be included in C# 12 or later.

Base for this is the csharplang-repository. So let's discover brand new features and how they could help us in our everyday life. We will see things like:

  • Compound assignments in object initializer
  • Discriminated unions
  • semi-auto properties aka field
  • ConfigureAwait(false) on assembly level
  • Exponentiation operator

Read the whole article

Preview image blogpost

Central nuget store for your UNO Platform App

With the newest UNO Platform update to .NET 6 we can leverage some cool things to simplify our dependency management. We combine .NET 6 with the new feature called Directory.Build.props to make that work.

Read the whole article

Preview image blogpost

When does Blazor (not) render?

This blog post whill shed some light on when Blazor renders your content. Of course there are obvious candidates, but there are also some things to be aware about.

Read the whole article

Preview image blogpost

Wrap Event based functions into awaitable Tasks - Meet TaskCompletionSource

You might have code where an object offers you an event to notify you when a specific operation is done. But event's can be tricky to use, especially when you want to have a continuous flow in your application.

That is where TaskCompletionSource comes into play. We can "transform" an event based function into something which is await-able from the outside world via the await keyword.

Read the whole article

Preview image blogpost

goto in action - The exception from the rule

A lot of developers will say never use goto. This keyword is bad as it promotes spaghetti code. But as so often in live the exception confirms the rules. Let's see where goto can increase the readability and maintainability.

Read the whole article

Preview image blogpost

What is the difference between C#, .NET, IL and JIT?

When you get started or even if you have quite some knowledge it can be confusing to juggle with those terms. So what is the difference between C# and .NET? And what does it have to do with IL and JIT?

Read the whole article

Preview image blogpost

Delegate, Action, Func, Lambda expression - What the heck!?

C# offers a lot of utility especially around the delegate topic. So let's see what exactly a delegate is and how the distinct types like delegate, Action, Func, Predicate, anonymous function, lambda expressions and MulticastDelegate behave. A lot to digest and discover so let's go.

Read the whole article

Preview image blogpost

The garbage collector in .NET - Part 2: Compacting

I already made a post about how the Garbage Collector works in .NET and also introduced the topic of Generation slightly. This article will look a bit more in detail into why we have those mechanisms in the first place, including the Large Object Heap.

Read the whole article

Preview image blogpost

ObjectPool - Rent and return some instances

Just imagine a car pool: There is a dealer which bought the car and lent's it to you. After a while you will return this car where you got it from. Much like that works an ObjectPool in C#. You can rent an expensive object from the pool and when you are done with it, you just return it. Sounds beautiful, doesn't it?

Let's explore the advantages and disadvantages of a ObjectPools and how they work.

Read the whole article

Preview image blogpost

Blazor with an RSS Feed

If you use a public Blazor Server application (like this blog is) and you want to expose an RSS Feed (I know kind of old school) you can perfectly do that with Blazor Server and a little help from a nuget package from Microsoft. Furthermore this guide is not only valid for Blazor but every ASP.NET Core endpoint.

Read the whole article

Preview image blogpost

How to unit test a RavenDB

RavenDB is a well known open-source document-oriented databse for .NET. And of course we want to test our logic and not only locally while developing, but also our continuous integration pipeline should be able to run our tests. So let's tackle exactly that.

Read the whole article

Preview image blogpost

The garbage collector in .NET

This article will talk about the garbage collector in .NET. Why do we have and need him? And why it is essential to understand the behavior to know what impact on our application he has.

Read the whole article

Preview image blogpost

Blazor with CancellationToken support

What happens when a user navigates away and still has a pending request to our server? Or what happens if we have a request which might take forever and wastes our resources?

Let's tackle these problems with a CancellationToken.

Read the whole article

Preview image blogpost

Stop using Finalizers in C#

Finalizers (historically referred to as destructors) are in C# since its dawn of time and are used to cleanup resources. But they should not used in every use-case and can harm your applications performance.

Read the whole article

Preview image blogpost

Tail-Recursion - Explained with the Fibonacci series

What is Tail-Recursion? We will discover this "special" form of recursion on the example of the Fibonacci series. Also we will check how much faster it is and why.

Read the whole article

Preview image blogpost

Why are sealed classes faster in C#? And should I seal them?

In C# we can add the sealed modifier to a class to indicate that no one is allowed to derive / inherit from that class. Let's have a look at the compiler in certain scenarios what happens if you seal a class.

Read the whole article

Preview image blogpost

Passing by value or by reference - What is faster?

When we are passing objects around we can do this either via reference or by value. Which of those two methods is faster?

To answer this question we have to dive into a bit of info about what happens exactly when you pass something around and how the other side will receive this.

Read the whole article

ReadOnlyCollection is not an immutable collection

In this blog post we discover how we can mutate a ReadOnlyCollection to have more or less entries than its original state. Readonly does not mean it is immutable. Also we will check out the ImmutableArray.

Read the whole article

Preview image blogpost

Is public const bad?

Is declaring a number or string as public const considered bad practice? Let's have a look what a const variable means in the first place. Let's find out and also check what are the alternatives.

Read the whole article

Preview image blogpost

Modal Dialog component with Bootstrap in Blazor

This short blog post will show you how to utilize Bootstrap to create a small and reuseable ModalDialogComponent.

Read the whole article

Preview image blogpost

4 Different ways of creating an array

In this blog post I will show you 4 different ways of creating an array and how they differ from each other.

Read the whole article

Preview image blogpost

default(MyStruct) vs new MyStruct() - what is the difference?

There are multiple ways to create a new struct, either via var myStruct = default(MyStruct) or via var myStruct = new MyStruct(); . Are there any differences?

Read the whole article

Preview image blogpost

From Zero to Production - Generate everything with a single button

This blog post will show you how to setup, from scratch, your GitHub repository so you can in a matter of a single click:

  • Run tests and build your application
  • Release the application for example to nuget
  • Create a Release on GitHub with Release notes
  • Update the documentation utilizing GitHub Pages and DocFx

Therefore we will build a "template" repository you can take as a foundation.

Read the whole article

Preview image blogpost

struct vs readonly struct vs ref struct vs record struct

C# knows struct since its down of time. But there are also recent additions like readonly struct, record struct and ref struct.

This article will show what are the differences between those 4.

Read the whole article

Preview image blogpost

Create a low allocation and faster StringBuilder - Span in Action

.NET ships a nice StringBuilder since the dawn of time or at least since the beginning of the framework itself. The intention is simple: If we need to concatenate a lot of strings we can't rely on the + operator as we introduce a lot of unnecessary allocations plus it is slow! That is where the StringBuilder jumps into the picture.

Why is that? Why is the StringBuilder better? And can we do better? Spoiler: Yes!

Read the whole article

Preview image blogpost

Reusable loading Bar Component in Blazor

In our Blazor components we often call a repository or web API which takes some time. So it is nice to indicate to an user what the current state is. That is why we will create a small indicator even with steps to indicate how far we are in the progress.

Read the whole article

Preview image blogpost

UNO Platform - Build a Todo App - Part 5

This is the last part of the series (for now 😄). In the last. Two parts are missing:

  • Drag and Drop the items from one lane to another
  • Save and load the state

And exactly those two things we will tackle. I also will give a small conclusion of my journey.

Read the whole article

Preview image blogpost

UNO Platform - Build a Todo App - Part 4

In the forth part we will take care of our newly created todo item. Until now we clicked on a button and that's all. Sure we have a nice form where we can enter the basic information, but that is all.

The time has come to put our element into the respective swimlane. We will also learn how to add further nuget packages to our project.

Read the whole article

Preview image blogpost

The Trie - A powerful data structure

A Trie is a common data structure used for example for auto completing words. We will discover how to built our own Trie and check how fast he competes against a "normal" Hashset.

Also we will build a TypeAHead input component which automatically offers us some suggestion based on our input. Of course, we will use our newly created Trie.

Read the whole article

Preview image blogpost

UNO Platform - Build a Todo App - Part 3

In the third part of our small mini series: "Building an todo app with the Uno Platform" we will dive deeper into creating a modal dialog where we can enter the details of our todo item. We will see how we can import additional Nuget packages and how we can leverage validation.

Read the whole article

Preview image blogpost

UNO Platform - Build a Todo App - Part 2

This is the second part of our small mini series, where we build a todo app Kanban style with the UNO Platform. In this episode we are laying some ground work as well as defining all of our requirements we want to achieve.

We will slowly start creating our first components and make everything work smoothly together.

Read the whole article

Preview image blogpost

UNO Platform - Build a Todo App - Part 1

This is the beginning of a mini series shedding some lights on the UNO Platform. The UNO Platform enables us to write code once and run it on a wide range of platforms (Windows, MacOS, Android, Linux, ...). So let's have a look at this. To do so we will create a small Todo App Kanban-style so we can organize our thoughts and work 😉

Read the whole article

Preview image blogpost

Using SSE in C# on the example of the sum of a list

SSE stands for Streaming SIMD Extensions. What does that exactly mean and how can we leverage that in our C# code?

This blog post will shed some light on this topic. Also we make a small comparison to PLINQ.

Read the whole article

Preview image blogpost

Decorator Pattern using the example of a cached repository

The decorator pattern is a common pattern in object oriented languages. It allows us to add behavior to an individual object without changing the object itself.

We will exactly that with a repository. We introduce a caching layer via the decorator pattern.

Read the whole article

Preview image blogpost

RequiredIf - Extend the validation in Blazor

Just imagine you have your beautiful model in a form. And Blazor is very kind and does validation for you. It is really straight forward because you can annotate your model with some attributes like RequiredAttribute to tell Blazor: "Hey this property has to be set, otherwise the form will not be submitted."

But what if you want to have that easy setup with attributes but also want to say to Blazor: "Hey this property has to be set, if the other property is true.* Well, that does not work out of the box. So let's make it together!

Read the whole article

Preview image blogpost

Directory.Build.props - Centralize your builds

MSBuild has several extensibility hooks to customize your build and today we discover one which let you centralized repeating aspects of your C# projects. Directory.Build.props

Read the whole article

Preview image blogpost

DebuggerTypeProxy - Displaying complex states in the debugger

With the DebuggerTypeProxy we have the possibility to show more complex states. This can be helpful in certain cases where an object for example has a lot of properties.

Read the whole article

Preview image blogpost

Blazor Performance Tuning - Good practices and advanced use cases

Blazor is a beautiful framework for building SPA's. One advantage is that those SPA's feel like native applications. We do not feel that stuff is necessarily loading. But for that we have to keep our code performant.

This guide will highlight some of the techniques to keep your Blazor app running smoothly. We will also cover some more advanced use cases.

Read the whole article

Heap, Stack, Boxing and Unboxing, Performance ... let's order things!

In this article I will shade some lights on some of the most used terms which seems very confusing especially for beginners: heap, stack and boxing and unboxing.

Furthermore we will also encounter internet wisdom like:

Value types get stored on the stack. Reference types on the heap

We discuss why this is wrong and what the hell performance has to do with it?

Read the whole article

Preview image blogpost

Prerendering Blazor Apps - How does it work / tips and tricks

Blazor comes with the option to prerender your webpage on the server. This works for the client-side version as well as the server side version of Blazor.

Let's have a look how does it work and what might be some pitfalls and how can we come around those.

Read the whole article

Preview image blogpost

Enum.Equals - Performance analysis

Did you know that you can spend 100x times longer depending how you compare your enums?

Of course we are speaking here in terms of nanoseconds but this story is much more then just numbers. We'll also talk about boxing and unboxing. So let's dive right into it.

Read the whole article

Preview image blogpost

Lazy load components with Blazor - Virtualize in Action

Since .NET5 we have the ability to "virtualize" a component.

But what exactly is that and how do we use it? This blog post will show you a lot of details about the <Virtualize> tag.

Read the whole article

Preview image blogpost

Generator-Function in C# - What does yield do?

Since the introduction of C# 2.0 we have the yield keyword with in combination with the IEnumerable<T> type works as a generator function. We can return elements one by one.

But how does that thing work internally? And what does it have to do with async / await?

Read the whole article

Preview image blogpost

Task vs ValueTask - The what's, when's and how's

Since .NET Core 2.0 the Type ValueTask. It seems that there is a lot of overlap between Task and ValueTask. So let's have a deeper look into ValueTask. Where should we use it and how should we use it properly? And also: where we should not use is.

Read the whole article

Preview image blogpost

ILGPU - Processing Data on your GPU (CUDA / OpenCL in C#)

If you ever needed a massive amount of data processed in parallel you might had a look at OpenCL or CUDA. Both are based on a subset of C to describe the program your GPU has to execute.

So let's have a look how we can achieve this in the .NET way. Furthermore I'll give you some insights about GPGPU (General-purpose computing on graphics processing units) in general. Also some limitations and big differences to conventional "CPU"-Programming.

Read the whole article

Preview image blogpost

static abstract interfaces and generic math

Besides the big announcements of .NET 6 there are also some smaller features. I want to show case a special one: static abstract interfaces. With this you have ability to extend the contract in that sense, that an implementing class has to provide also static methods. This feature is right now flagged as preview, but you can use it if you want.

This also enables generic math operations on an interface level.

Read the whole article

Preview image blogpost

A better enumeration - Type safe from start to end

Enumerations are one of the fundamental value types in C#. enum's are handy if you have a constrained set of allowed values. But the enum type also has a lot of drawbacks. Personally, one major issue for me is that you can't define methods inside the enum. Plus, you can just pass them invalid values and it just works (Todd Howard I'm looking at you).

So why not make a lightweight alternative which removes a lot of the shortcomings of an enum?

Read the whole article

Preview image blogpost

API Versioning in ASP.NET Core made easy

How can we have versioning with a public facing REST API in ASP.NET Core? This blog post will show you the foundation how to setup and configure versioning. Furthermore I will give you some ideas how to structure your code and what kinds of versioning you can do.

In the end you should be able to have the same endpoints with multiple versions.

Read the whole article

Preview image blogpost

IEnumerable vs IQueryable - What's the difference

.NET brings two types which seem very similiar

  • IEnumerable
  • IQueryable

What is the difference? Most are familiar with using IQueryable when we want to go to the database and back. But why not using IEnumerable?

Read the whole article

Tactical Design Patterns in C# - Part 1: Creational

This guide will give an overview of common design patterns in C#. We'll also have a look what is there advantage and how can we implement them. Let's start with creational design patterns.

Read the whole article

Preview image blogpost

Shorts: foreach on type without IEnumerable

Is it possible to have a foreach loop over a type which does not implement IEnumerable? Yes it is.

Read the whole article

Preview image blogpost

Task.WhenAny - How to cancel other tasks

This short post will give an overview how to cancel all remaining tasks once Task.WhenAny finishes. Plus how Task.WhenAny behaves in different circumstances.

Read the whole article

Preview image blogpost

A story about boxing / unboxing and string interpolation in C#

A story about boxing / unboxing and string interpolation in C#. What has string interpolation to do with boxing / unboxing and what's the impact?

Read the whole article

Preview image blogpost

Quickly asked: Should I use unsigned integers (uint, uint8, ...) in C#?

Should I use uint as a type in my library / website / program? For example when iterating through an array? I mean that thing can't be smaller than 0!?

So let's have a look.

Read the whole article

Preview image blogpost

Async Await Pitfalls / Guidelines - .NET User Group Zurich Presentation

On 6th of July I had the honor to present some topics about async/await. Mainly:

  • What is asynchronous programming
  • Deadlocks and ConfigureAwait
  • How does the state machine work
  • Pitfalls and general Guidelines
  • ValueTask

You'll find all the slides and the whole talk in the blog.

Read the whole article

Preview image blogpost

Tutorial Unit and E2E Testing in Blazor - Part 1

This blog post should give you an easy and good introduction how to unit and end-to-end test your Blazor Application. Furthermore it does not matter if we are running server side or client side aka WebAssembly. The main two libraries we are using is first bUnit for unit-testing and Playwright for end-to-end testing. So let's dive in!

Read the whole article

Preview image blogpost

My first Post

Welcome to my blog and my first post

In this article I will show you why I created my own blog-software from scratch and why I have a blog in the first place. Short answer: I like to know how to create a blog and I like blazor. Long answer you will find in the post.

Read the whole article

An error has occurred. This application may no longer respond until reloaded. Reload x