C# – Deserialize JSON using different property names

When JSON property names and class property names are different, and you can’t just change the names to match, you have three options: These options affect both deserialization and serialization. Let’s say you have the following JSON with camel-cased property names: Here’s an example of using the JsonPropertyName attribute: Note: The Newtonsoft equivalent is [JsonProperty(“title”)] … Read more

C# – Deserialize JSON with a specific constructor

When your class has multiple constructors, you can use the JsonConstructor attribute to specify which constructor to use during deserialization. Here’s an example. The Person class has two constructors. I put the JsonConstructor attribute on one of the constructors: Note: JsonConstructor for System.Text.Json was added in .NET 5. Now deserialize a JSON string to the … Read more

Redirect a request in ASP.NET Core

Redirecting a request means returning a response with redirect status code (3xx) and a redirect URL in the Location header. The client uses this info to follow the redirect (which means making a request to the redirect URL). You can redirect by using a helper method (from ControllerBase) or returning a RedirectResult. I’ll show several … Read more

C# – Call a constructor from another constructor

To call one constructor from another one, you have to use the constructor chaining syntax, like this: This means when you use the Person(string name) constructor, it’ll first call the Person(string name, string birthDate) constructor. If the constructor is in a base class, use base() instead of this(): Employee subclasses Person. So calling base(name) here … Read more

C# – Handling redirects with HttpClient

HttpClient handles redirects automatically. When you send a request, if the response contains a redirect status code (3xx) and redirect location, then it’ll send a new request to the redirect location. You can turn off this auto-redirect behavior by passing in an HttpClientHandler with AllowAutoRedirect=false. This prevents it from following redirects automatically, and allows you … Read more

The required library hostfxr.dll could not be found

Problem You are trying to run a .NET executable and you get the following error: A fatal error occurred. The required library hostfxr.dll could not be found.If this is a self-contained application, that library should exist in [C:\MyApp].If this is a framework-dependent application, install the runtime in the global location [C:\Program Files\dotnet] or use the … Read more

C# – Connect to a MySQL database

The simplest way to connect to a MySQL database in a .NET project is to use the MySql.Data package (from Oracle). It provides classes that implement the standard ADO.NET interfaces (such as IDbConnection). First, add the MySql.Data package to your project (this is using View > Other Windows > Package Manager Console): Now use the … Read more

C# – How to use SortedSet

When you have a collection of elements that you’re continuing to add to, and need to keep the objects in sorted order at all times, you can use SortedSet. Internally, it uses a tree data structure to keep elements in sorted order (O(log n) insertion). This is far more efficient than repeatedly sorting a list … Read more

C# – Deserialize JSON to a derived type

The simplest way to deserialize JSON to a derived type is to put the type name in the JSON string. Then during deserialization, match the type name property against a set of known derived types and deserialize to the target type. System.Text.Json doesn’t have this functionality out of the box. That’s because there’s a known … Read more

C# – Populate an existing object with JSON

Normally when you’re working with JSON, you deserialize it to a target type and get back an initialized and fully populated object. How about if you need to initialize an object yourself, and then populate it with JSON later? For example, let’s say you want to load the following JSON array into a case-insensitive HashSet: … Read more

C# – How to implement GetHashCode() and Equals()

The simplest way to implement GetHashCode() is to use the built-in System.HashCode.Combine() method and pick the properties you want to include. Let it do the work for you. Furthermore, the simplest way to implement Equals() is to use the is operator and compare all the properties. Here’s an example: Note: Use (Title, Year).GetHashCode() in versions … Read more

C# – How to ignore JSON deserialization errors

One error during JSON deserialization can cause the whole process to fail. Consider the following JSON. The second object has invalid data (can’t convert string to int), which will result in deserialization failing: With Newtonsoft, you can choose to ignore deserialization errors. To do that, pass in an error handling lambda in the settings: This … Read more

C# – Deserialize a JSON array to a list

When you’re working with a JSON array, you can deserialize it to a list like this: This deserializes all of the objects in the JSON array into a List<Movie>. You can use this list object like usual. Note: All examples will use System.Collections.Generic and System.Text.Json. I’ll exclude the using statements for brevity. Example – JSON … Read more

C# – Deserialize JSON as a stream

Here’s an example of deserializing JSON from a file as a stream with System.Text.Json: Stream deserialization has three main benefits: In this article, I’ll go into details about these benefits and show a few other stream serialization scenarios. Benefits of deserializing as a stream Performance There are two ways to deserialize JSON: Deserializing a stream … Read more

C# – Examples of using GroupBy() (Linq)

Here’s an example of using the Linq GroupBy() method to group coders by language: This example outputs the following: GroupBy() produces groups that contain the grouping key (i.e. Language) and the list of objects in the group (i.e. the Coder objects). The GroupBy() syntax is complex because it supports many scenarios. You can select one … Read more

C# – Get argument names automatically

You can use the CallerArgumentExpression attribute to automatically get the name of an argument being passed into a method: Note: CallerArgumentExpression was added in .NET 6. Here’s an example to show what CallerArgumentExpression does: Calling this method outputs the following: You use the CallerArgumentExpression attribute with a default string parameter (i.e. string argumentName = null). … Read more

C# – Hide a method from the stack trace

When you want to exclude a method from showing up in the stack trace, you can apply the StackTraceHidden attribute to the method: Note: This attribute was added in .NET 6. You can apply StackTraceHidden to a class to hide all of its methods from the stack trace: Use StackTraceHidden with throw helper methods StackTraceHidden … Read more

C# – How to use JsonExtensionData

Use the JsonExtensionData attribute (in System.Text.Json) to deserialize properties that aren’t part of the class. Without this, JSON fields that don’t match a property are simply ignored and the returned object will have null properties. Here’s an example of adding this attribute to a dictionary property: Now when you deserialize JSON to this Person class, … Read more

C# – Property order with System.Text.Json

You can use the JsonPropertyOrder attribute to control the order that properties get serialized. You specify the order as an integer, and it serializes the properties in ascending order. Here’s an example: Note: Properties have a default order value of 0. Now serialize an object to JSON: This generates the following JSON: Notice the properties … Read more