Posts about C#

Performance comparison of Regex in .NET

April 12th 2024 C# .NET BenchmarkDotNet

If you've used regular expressions a lot in .NET, you most likely already know that by using the Compiled option you can improve the run time performance a lot at the cost of higher initialization time. What you might not know is that since .NET 7 you can use a source generator instead to avoid that initialization cost.

Choosing extension over instance method

March 22nd 2024 C# .NET

Extension methods are a great way to extend classes you don't own with what looks like an instance method. Therefore, you usually don't need to create extension methods for a class from the same assembly because you could simply add the same code to that class as an instance method. However, not everything you can do with an extension method can also be done with an instance method.

IAsyncEnumerable performance benefits

February 9th 2024 C# .NET BenchmarkDotNet

Asynchronous streams (i.e., the IAsyncEnumerable interface) were one of the new features in C# 8. However, it didn't get as much attention as some others. Even today, the feature is rarely used and not well known among C# developers, although it can make the code faster and easier to understand in some cases.

Auto-formatting C# code

January 5th 2024 C#

I'm a big fan of Prettier, and I'm using it for auto-formatting code in any web projects I'm working on. Unfortunately, it doesn't support C#. I've been writing about alternatives in the past, although they weren't exactly on the same level. Only recently I learned about CSharpier, and of course, I had to try it out.

Benefits of collection expressions

October 20th 2023 C#

Collection expressions are a new feature of C# 12. At first glance, it's very similar to collection initializers, and you might wonder what benefits it brings except for the slightly different syntax. Let's take a closer look.

Primary constructors and inheritance pitfalls

October 13th 2023 C#

In my previous blog post, I described a case in which you can have the same data stored in two fields when using primary constructors. You can run into a similar problem when using primary constructors in combination with inheritance incorrectly.

Double storage in class with primary constructor

October 6th 2023 C#

.NET 8 is going to be released soon and with it C# 12 as well. Its largest new feature are most likely primary constructors. With this new feature, you can mostly get rid of trivial constructors used only for assigning parameter values to private fields. However, if you're not careful, you might end up with the same piece of data being stored in two fields which can easily diverge and cause bugs in your code.

Attributes in EF Core migrations

September 8th 2023 EF Core C#

Recently, I was tasked with troubleshooting an EF Core migrations issue in a codebase I was not familiar with. The problem was that the Update-Database command didn't detect the migration in the project. It behaved as if the migration file wasn't present at all.

Nullable error with lazy loading in EF Core

September 1st 2023 EF Core C#

EF Core is pretty strict about nullable reference types. I wrote about this before in the context of migrations, but it also affects loading of data from the database. If you try to load a null value into a non-nullable string property, a SqlNullValueException will be thrown.

Nullable value types in C# attributes

November 18th 2022 C#

Attributes in C# support only a limited number of parameter types. If you want to use other types, such as Nullable<int>, you must find a way around this limitation.

Explicit type conversion in C# foreach loop

November 11th 2022 C#

If you are a C# programmer, I am sure you use foreach loops regularly and believe you are well acquainted with this language construct. So do you think the following code can be compiled?

Dangers of a hidden PropertyChanged event

August 19th 2022 C# MVVM Xamarin

I recently spent a considerable amount of time looking for a reason why the data binding in one of the Xamarin.Forms pages was not working. When I found the cause, it made perfect sense. But it was not easy to identify it.

Nullable reference types and nullability in EF Core

August 12th 2022 EF Core C#

Nullable reference types have a greater impact on projects using Entity Framework Core than other projects. Although this is well documented, I have found that many developers are not aware of this.

Throwing null argument exceptions

December 24th 2021 C# .NET

NullReferenceException is probably one of the most common exceptions in .NET. It is thrown whenever you try to access a member of a reference type that is currently set to the value null. With the nullable reference types introduced in C# 8, the compiler can now warn you if you try to do this, so you can add a null check to prevent the exception from being thrown. Null checking code is simple, but very repetitive and potentially error-prone.

Awaiting Google Play services tasks

April 16th 2021 Xamarin Android Async C#

Thanks to Xamarin, C# developers can use a lot of their existing knowledge even when interacting with native Android (and iOS) APIs. However, some APIs still break the idioms we're used to in .NET. When I recently had to integrate Firebase Cloud Messaging into a Xamarin application, I encountered an asynchronous call that couldn't be awaited. The method even returned a Task. It just wasn't the right Task.

Synchronous async method implementation

April 9th 2021 Async C#

Interfaces usually have methods that return tasks because they were designed to be asynchronous. But how should you implement such a method when you don't need to call any asynchronous methods inside it?

Constructing Immutable Objects with a Builder

June 12th 2020 Design Patterns C#

Immutable objects can't change after they've been created. Because of this, all data needed for their initialization must be passed into them through the constructor. This can result in constructors with (too) many parameters. With the builder design pattern, this can be avoided.

Be Careful with Using Declarations in C# 8

January 3rd 2020 C#

One of the less talked about new features in C# 8 are using declarations. That's not too surprising since it's essentially just syntactic sugar for using statements. However, the exact location in the code where an object is disposed might be different than with using statements. Since other methods might be called implicitly when an object is disposed, this might change the behavior of your code making it incorrect.

Slides and Code from .NET DeveloperDays

October 25th 2019 C# Speaking

In August, I was invited by the organizers of the .NET DeveloperDays conference to have a session about C# 8 in Warsaw at the end of October. After a few exchanges with them and a short consideration, I decided to take on the challenge of speaking at a conference of such size for the first time. As promised at the end of my session there, I'm making the slides and sample code available for download.

Slides and Code from My SLODUG Session

September 13th 2019 C# Speaking

This Tuesday, the Slovenian Developers User Group organized the annual meetup with the highest-voted sessions from the NT conference. Unfortunately, the second speaker couldn't make it back to Slovenia in time due to unforeseen circumstances. Since we couldn't find a different speeker on such a short notice my session about C# 8 was the only one at the event.

Slides and Code from NT Conference 2019

Yesterday the NT Conference 2019 concluded in Portoro┼ż. This year I had three sessions there. On Tuesday, I talked about the new language features in C# 8. On Wednesday, I repeated my session about application architecture from this year's Global Azure Bootcamp. My final session on Thursday was about global tools in .NET Core.

My Book About C# and .NET Is Available

February 1st 2019 Book C# .NET Framework .NET

Since this week, The Absolutely Awesome Book on C# and .NET is finally available for order in its final form: in all eBook formats and with the accompanying source code.

Variance with Generic Inputs and Outputs

January 4th 2019 C#

Although I could say that I understand covariance and contravariance, I still need to pause for a moment and think it over whenever I have to deal with them. It all gets even more complicated if generic type arguments aren't directly in the role of an input parameter or a return value.

No Support for Tuples in Expression Trees

December 7th 2018 C# .NET .NET Framework EF Core

Tuples, as added to C# 7, can be a nice alternative to anonymous types in LINQ when you only want to return a subset of values from the queried type. Before tuples, this was only possible by creating an anonymous type in the Select method. Now you can create a tuple instead. However, if you try to do that with EF Core, the code won't compile. How come?

FormattableString as Method Parameter

September 21st 2018 C# EF Core

Interpolated strings in C# 6 introduced a simplified syntax for most use cases of String.Format. The new syntax has several immediate advantages, but its internal implementation also lends itself to some innovative usage. In EF Core 2.0, interpolated strings can be used to write safe SQL queries with shorter syntax. Let's take a look at how this is implemented.

No Custom Conversions for Interfaces in C#

September 14th 2018 C#

There's a lot of flexibility in type conversions in C#. On top of built-in implicit and explicit conversions, you can also define custom conversions. However, you might not be aware that these are not supported for interfaces.

My Sessions at NT Conference 2018

May 25th 2018 C# Unit Testing .NET Speaking

It's the week of NT Conference 2018. I had two sessions this year. On Tuesday, I talked about a selection of common C# gotchas which can surprise even an experienced C# developer. In my second session, I explained the benefits of continuous testing and showed how to configure it for a .NET Core project in Visual Studio 2017 and Visual Studio Code.

Advent of Code 2016

For the second year in a row, I spent a significant amount of time in December solving the Advent of Code programming puzzles. Before writing the first line of code, I created a repository for my solutions. Unlike last year, I wanted to have all the code readily available for future reference. More than once, I actually looked up previous solutions while solving a more recent puzzle.

Slides and Code from My Sessions at Cancel Conference

September 17th 2016 Async C# .NET Speaking

This week the second community organized Cancel conference was taking place in Ljubljana. It spanned over two days. Thursday was the main conference day with 20 sessions grouped in 4 tracks. On Wednesday afternoon preconf was organized at the premises of Microsoft Slovenia. I had my sessions on both days.

Slides and Code from My Sessions at NT Conference

May 20th 2016 Async C# Speaking

It's May again, which means the annual NT Conference was taking place in Portoro┼ż at the beginning of this week. This year I had two sessions scheduled, the first one on Monday and the second one on Tuesday.

Strings in .NET Are Not Null Terminated

February 7th 2016 C# .NET Framework

Are you used to the fact that strings are null-terminated? Well, in .NET framework they are not. In this article I explore the consequences of that, explain the circumstances under which you might stumble across it, and suggest, how to avoid being affected by it.

Can a Static Field Be Initialized Multiple Times?

December 12th 2015 C# Universal Apps

Under what circumstances can a static field be initialized multiple times? C# language specification makes it pretty clear that static fields are initialized only once, before the class is first used. This meant, it was time for some creative thinking, when I encountered an issue, seemingly caused by the static field being initialized multiple times.

Resources From My Sessions at NT Conference

This year I had 2 sessions of my own at NT conference: What's New in C# 6 and Diagnostic analyzers in Visual Studio 2015. Slides and demos for both them are available for download.

Resources from My Visual Studio 2015 Session at TechDays

January 31st 2015 Roslyn NuGet Unit Testing C# Speaking

On Tuesday Microsoft Slovenia organized the second TechDays event leading up to the 20th NT conference. The event consisted of 4 tracks; I had the opening session for the Visual Studio 2015 track. As always slides and demos from my session are available for download.

Debugger Doesn't Trigger Static Type Initialization

September 1st 2014 Debugging Visual Studio C#

According to the C# language specification, the static field initializer should execute before it is accessed for the first time. As it seems, looking up the field value in debugger doesn't trigger the initializer.

Improve ReSharper Static Analysis Using Annotation Attributes

August 18th 2014 ReSharper Static Analysis C#

Static code analysis is a very useful feature of ReSharper. The generated warnings can help you fix bugs which might otherwise remain unnoticed. Unfortunately static analysis is not perfect and it might detect false positives. There are a couple of ways to tell it not to warn us about specific ones any more.

Book Review: C# Tips

August 14th 2014 C# Review Book

No matter how well versed you with C#, the book will teach you something new about it or at least remind you about the stuff you already know without being consciously aware of it. Since the author lets you choose the price for the book, you'll certainly get your money's worth from it.

Book Review: OUYA Game Development by Example

I can sincerely recommend the book to anyone, trying to get a glimpse into the world of game development. It can really only serve as the first step on the path to becoming a game developer, but it's definitely enough to see if that's something for you and worth exploring further.

Dynamic Binding of Static and Instance Methods

March 10th 2014 C#

The compiler does not remove static methods when calling through an instance because it does not necessarily know that you are calling through an instance. Because there are situations where it is ambiguous whether you're calling through an instance or a type, it defers deciding which you meant until the best method has been selected.

Using Abstract Override in C#

October 28th 2013 C#

Recently the abstract override language construct has been brought to my attention. Knowing about both keywords, there isn't much doubt what it means to the compiler. The combination of both keywords can only be used in two cases.

Why Might Using Public Const Not Be a Good Idea?

November 28th 2010 C# MSIL

While reading an article on the difference between const and readonly it surprised me that changes to public consts in the referenced assembly don't affect the referencing assembly unless it is recompiled using the changed referenced assembly. The C# Reference doesn't hint at such behavior at all, which means it's time for further exploration.

Useful PInvoke Resources

May 3rd 2006 Native Interop C#

For anybody else like me out there who hasn't done more than an occasional DllImport call or two, the following resources should help getting to grips with the PInvoke basics.

Static Class Constructors Should Never Throw an Exception

February 23rd 2006 C# .NET Framework

No matter what you're doing in the static constructor, never allow it to throw an exception unless the problem is indeed fatal and you intend to quit the program immediately. In all other cases provide reasonable defaults and handle changed circumstances elsewhere in the code.