C# – Using Channel as an async queue

The Channel class (from System.Threading.Channels) is a non-blocking async queue. It implements the producer-consumer pattern, which has two parts: Compare this with using BlockingCollection, which is a blocking concurrent queue. In this article, I’ll show how to use a Channel. 1 – Create the Channel The first step is to create the Channel object. Here’s … Read more

ASP.NET – Async SSE endpoint

Server-Sent Events (SSE) allow a client to subscribe to messages on a server. The server pushes new messages to the client as they happen. This is an alternative to the client polling the server for new messages. In this article I’ll show how to implement the messaging system shown in the diagram below. This uses … Read more

C# – Async Main

The Async Main feature was added in C# 7.1 and works with all overloads of the Main() method. To make the Main() method async, add async Task to the method signature, like this: This is syntax sugar that compiles down to calling GetAwaiter().GetResult() on whatever you’re awaiting. In other words, it’s equivalent to doing the … Read more

C# – Cannot use a lambda expression as an argument to a dynamically dispatched operation

Problem You are trying to use a lambda expression on a dynamic object and get the following compiler error: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. As an example, the following code causes this error: Solution Cast the … Read more

Error: Cannot convert null to type parameter ‘T’

Problem You’re trying to return null from a generic method and you’re getting the following compiler error: Cannot convert null to type parameter ‘T’ because it could be a non-nullable value type. Consider using ‘default(T)’ instead You can’t return null because the compiler doesn’t know if T is nullable. Solution There are a few options … Read more

C# – Can’t pass decimal parameter in DataTestMethod

I have a parameterized unit test with decimal parameters. When I run the test, I get the following exception: System.ArgumentException: Object of type ‘System.Double’ cannot be converted to type ‘System.Decimal’. Solution Change the parameters to doubles and convert them to decimals inside the test method. Why is it throwing an exception? You have to pass … Read more

C# – How to make concurrent requests with HttpClient

The HttpClient class was designed to be used concurrently. It’s thread-safe and can handle multiple requests. You can fire off multiple requests from the same thread and await all of the responses, or fire off requests from multiple threads. No matter what the scenario, HttpClient was built to handle concurrent requests. To use HttpClient effectively … Read more

C# – How to use FileSystemWatcher

You can use the FileSystemWatcher class to detect file system changes, such as when a file is created, deleted, modified, or renamed. When a change happens, it raises an event that you can handle. This is an event-based alternative to polling for file changes. In this article, I’ll show how to use FileSystemWatcher to detect … Read more

C# – How to test that your code can handle another culture’s date format

Let’s say you have code that converts a string to a DateTime with DateTime.Parse(): By default, DateTime.Parse() uses CultureInfo.CurrentCulture to figure out the date format. The current culture ultimately comes from your OS settings. So when you run this code on a computer that is using the en-US locale, the current culture will automatically default … Read more

.NET – Signing code with a certificate

You’re given .PFX code signing certificate and told to sign your code. What does this mean, and how do you do it? What is code signing? Signing code means creating a digital signature on an executable file by using a code signing certificate. When your code is executed, your organization’s security software will check that … Read more

C# – Use Convert.ChangeType to convert string to any type

You can use Convert.ChangeType() to convert from a string to any type, like this: Normally you’d call the specific type converter method, such as when you’re converting a string to an int. However, sometimes it makes sense to use the generalized type converter method – Convert.ChangeType() – instead of hardcoding the calls to specific type … Read more

C# – How to implement the plugin pattern

In this article, I’ll explain how to implement the plugin pattern. This approach uses a generic plugin loader that solves many real world problems when loading plugins in .NET. Besides being generic, this plugin loader also solves the following real world problems when working with plugins: If you find that this generic plugin loader doesn’t … Read more

Error: Sequence contains no elements

Problem When you call .First() on an empty IEnumerable, you get the following exception: System.InvalidOperationException: Sequence contains no elements Solution Option 1 – Use .FirstOrDefault() instead of .First() When the IEnumerable is empty, .FirstOrDefault() returns the default value for the type. For reference types this returns null. For value types this returns 0 or that … Read more

C# – How to switch on type

Sometimes you may find it necessary to have conditional logic based on an object’s type. The simplest way to do this is to switch on the type, like this: This feature is called type pattern matching. Before this feature was added (in C# 7), you’d have to use a bunch of if-else’s and check the … Read more