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

WinForms – Date and time input

When you need to let the user select a date and/or time of day, you can use the DateTimePicker control: You can set the control properties in the UI or programmatically: If you don’t set an initial value, it’ll default to DateTime.Now (at the time the code is executed). The value the user picked is … Read more

C# – Get the last day of the month

The last day of the month is the number of days in that month. To get the number of days in a month, use DateTime.DaysInMonth(year, month): This outputs the following: Notice that it handles leap years (2024) appropriately. Using the number of days in the month, you can get the last day of the month: … Read more

C# – How to use JsonConverterAttribute

You can use JsonConverterAttribute (from System.Text.Json) to apply a specific JsonConverter to a property. Apply this attribute on a property and specify the JsonConverter type to use, like this: In this example, it’s applying ExpirationDateConverter (a custom JSON converter) to handle the ExpirationDate. For reference, here’s ExpirationDateConverter’s definition: Now serialize the object to JSON: Here’s … Read more

C# – Changing the JSON serialization date format

When you serialize a date with System.Text.Json, it uses the standard ISO-8601 date format (ex: “2022-01-31T13:15:05.2151663-05:00”). Internally, it uses the built-in DateTimeConverter class for handling DateTime, which doesn’t give you a way to change the date format. To change the date format, you have to create a custom JSON converter and pass it in: This … Read more

C# – Using top-level statements

The top-level statements feature makes the Main() method implicit. This feature was added in C# 9 (.NET 5) with the purpose of decluttering a project’s entry point. Here’s what a console app looks like using a top-level statement: The compiler generates the Main() method implicitly from the top-level statements. The code above is functionally equivalent … Read more

C# – Convert an object to JSON

Converting an object to a JSON string is referred to as serialization. The best way to do serialization is by using a good JSON serializer. There are two primary options: I’ll show examples of both options below. Using JsonSerializer.Serialize() (in the built-in System.Text.Json) Here’s an example of using the built-in JsonSerializer.Serialize() (in System.Text.Json) to convert … Read more

C# – Get inserted identity value with Dapper

When you insert a record into a table with an identity column, the value for the identity column is automatically generated for you. The simplest way to get the inserted identity value is to put OUTPUT INSERTED.<identity column name> in the insert statement: To get the output value with Dapper, use ExecuteScalar<int>(): This inserts the … Read more

Error MSB4226 Microsoft.TextTemplating.targets not imported

Problem You have a project that is using text templating (such as for auto-incrementing the version number) and you’re upgrading to a new version of Visual Studio. When you open the project, you get error messages about not being able to import the Microsoft.TextTemplating.targets project: Project “…\v16.0\TextTemplating\Microsoft.TextTemplating.targets” was not imported by “…SomeProject.csproj” at (7,3), due … Read more

C# – Adding dynamic parameters with Dapper

The simplest way to add dynamic parameters when executing queries with Dapper is by passing in Dictionary<string, object>, like this: Read more about how to add items to a dictionary. You can also add dynamic parameter by using the DynamicParameters class. You can use whichever approach is simplest in the given scenario. In this article, … Read more

C# – Using SQL transactions with Dapper

When you want to execute multiple SQL commands with Dapper in a transaction, using TransactionScope is the simplest option. Here’s an example of how to use it: When you call TransactionScope.Complete(), it commits the transaction. If you don’t call Complete(), it’ll rollback the transaction once it leaves the TransactionScope block. This keeps the code nice … Read more

C# – Execute a SELECT query with Dapper

You can query the database with Dapper by using Query() with a SELECT, specifying the type to map the results to, and optionally adding parameters. Here’s an example: Note: It returns an empty list when there’s no results. Dapper abstracts away the repetitive code involved in executing SQL queries, including mapping parameters and query results. … Read more