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!
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!
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".
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
.
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.
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!
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!
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.
I came across a very annoying "issue" with LINQ joins (left joins) in Entity Framework where the compiler drove me nuts!
I am a great fan of API tests. I do like to utilize the WebApplicationFactory
for this. I even wrote some articles about this in the past "Introduction to WebApplicationFactory". But what if we need to "mock" HttpClient
calls inside our tests?
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.
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.
Even though it was introduced in .NET 7, I came across recently the AsParametersAttribute
. Let's have a look what it is good for.
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.
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?
.NET natively knows UUID v4 aka Guid.NewGuid()
. But with preview 7 we get Version 7 of UUID's natively.
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.
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.
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!
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?
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!
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!
In today's short post, I will show you how to cancel a Task with multiple inputs (aka multiple CancellationToken
s) using CancellationTokenSource
and CancellationTokenSource.CreateLinkedTokenSource
.
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.
The latest preview (.NET 9 preview 4) brought another caching structure to the .NET world - so let's order some things here.
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?
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.
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.
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.
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.
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.
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?
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.
C# 13 might get a new feature soon that allows ref
and unsafe
in iterators and async methods.
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!
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.
I recently discovered this small but very useful utility in xUnit: TheoryData<T>
.
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.
SearchValues,
which were introduced with .NET 8 will become an upgrade and becomes more usable! Let's see how.
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.
In the old .NET Framework days, you could use the BinaryFormatter
class to serialize and deserialize objects. This can be convenient for cloning or storing some session states. As the BinaryFormatter
has some serious security concerns, the .NET team marked it as obsolete (as error) in .NET 7 and onwards.
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!
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.
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.
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.
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.
This blog post describes my journey writing a new interceptor for .NET 8. This is not meant as a general tutorial, even though I will showcase some of the code samples.
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.
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
.
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/
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.
In this article we will create a class, aka a reference type on the stack, and therefore don't use any managed memory!
Let's drop some "useless" knowledge here. Interfaces can have private methods. This comes with the C# 8 feature: "Default interface methods".
Ever wondered how to use TailwindCSS with Blazor? Let's make it work!
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#.
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.
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.
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.
.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.
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.
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.
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.
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#.
Are these two expressions the same?
public class MyClass
{
public int A { get; } = Random.Shared.Next(1000);
public int B => Random.Shared.Next(1000);
}
Enum
s 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.
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.¨
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.
The .NET 8 preview 7 will bring another exciting feature some of you probably awaiting for a long time: Keyed services.
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!
With the famous BenchmarkDotNet library you can benchmark a lot - but it doesn't stop with a single .NET version. You can benchmark multiple versions of the same code that targets different runtimes!
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.
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.
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!
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?
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!
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
?
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!
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.
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.
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?
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?
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.
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.
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.
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
.
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.
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.
In this blog post, we will have a look at the different log levels and how to control them.
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.
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.
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.
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.
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).
In this short blog post, I will show you 5 useful extensions for Task
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!
In this blog post, we will explore the use of SIMD instructions to speed up LINQ queries. We will use the Vector
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!
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.
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.
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.
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.
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.
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.
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.
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!
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.
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.
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.
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.
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(...));
.
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.
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.
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.
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.
.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.
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.
... 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.
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!
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.
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!
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);
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.
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
.
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.
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.
Many know that you can take ReadOnlySpan<char>
objects when dealing with string
s. 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
.
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!
.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.
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.
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?
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.
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.
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.
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.
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.
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.
.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.
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.
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.
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
.
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!
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?
This edition has the following infographics:
DebuggerDisplayAttribute
ExceptionDispatchInfo
implicit
and explicit
operator.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.
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?
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.
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.
This edition has the following infographics:
ConfigureAwait
on IAsyncDisposable
foreach
struct
null
for a Task
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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".
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:
field
ConfigureAwait(false)
on assembly levelWith 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.
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.
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.
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.
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?
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.
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.
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.
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.
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.
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.
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
.
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.
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.
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.
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.
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
.
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.
This short blog post will show you how to utilize Bootstrap to create a small and reuseable ModalDialogComponent
.
In this blog post I will show you 4 different ways of creating an array and how they differ from each other.
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?
This blog post will show you how to setup, from scratch, your GitHub repository so you can in a matter of a single click:
Therefore we will build a "template" repository you can take as a foundation.
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.
.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!
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.
This is the last part of the series (for now 😄). In the last. Two parts are missing:
And exactly those two things we will tackle. I also will give a small conclusion of my journey.
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.
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.
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.
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.
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 😉
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.
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.
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!
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
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.
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.
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?
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.
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.
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.
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
?
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.
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.
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.
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
?
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.
.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
?
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.
Is it possible to have a foreach loop over a type which does not implement IEnumerable
?
Yes it is.
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.
A story about boxing / unboxing and string interpolation in C#. What has string interpolation to do with boxing / unboxing and what's the impact?
EF Core 6 is right in front of our door and it looks very promising. In this blog post I will show what new features are to come.
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.
On 6th of July I had the honor to present some topics about async/await. Mainly:
You'll find all the slides and the whole talk in the blog.
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!
I am looking forward to give a talk about some insights and pitfalls of async
/ await
.
I will talk about the differences between asynchronous and parallel programming. Also a brief outlook how the state machine internally works. Feel free to join here: https://www.meetup.com/dotnet-zurich/events/278916769/
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.