C# – Convert a string to an int

There are three ways to convert a string to an int: I’ll show examples of using these approaches. Use int.Parse() int.Parse() takes a string and converts it to a 32-bit integer. Here’s an example of using int.Parse(): When conversion fails int.Parse() throws an exception if it can’t convert the string to an int. There are … Read more

ASP.NET Core – Control the graceful shutdown time for background services

ASP.NET Core gives you a chance to gracefully shutdown your background services (such as cleaning up and/or finishing in-progress work). By default, you’re given a grand total of 5 seconds to shutdown all background services. If you need more time than this, there are a few ways to control the graceful shutdown time, which I’ll … Read more

How to debug .NET source code in Visual Studio

When you’re using the Visual Studio debugger to step through your code, sometimes it’s useful to be able to step into the .NET source code. I had to do this recently to figure out why my ASP.NET Core code wasn’t behaving as expected. You can enable .NET source code debugging with the following steps: Now … Read more

C# – JSON deserializer returns null properties

Let’s say you have the following JSON: When you go to deserialize it, you notice that all or some of its properties are null (or default for value types): This outputs the following (because person.Name is null and person.Pets is 0): The data is definitely there, so why did it set these properties to null … Read more

C# – Ignore null properties during JSON serialization

By default, null properties are included during JSON serialization like this: There are two ways to ignore null properties: In this article, I’ll show examples of these two ways to ignore null properties. I’ll show how to do it with System.Text.Json and Newtonsoft. Ignore null properties with System.Text.Json Use JsonIgnoreCondition.WhenWritingNull to ignore null properties. You … Read more

C# – Nullable Reference Types feature basics

The main purpose of the Nullable Reference Types (NRT) feature is to help prevent NullReferenceExceptions by showing you compiler warnings. You can make a reference type nullable (ex: Movie? movie) or non-nullable (ex: Movie movie). This allows you to indicate how you plan on using these references. The compiler uses this info while analyzing actual … 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# – 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

ASP.NET Core – How to unit test an ApiController

The key to unit testing an ApiController class is to mock out all of its dependencies, including the controller’s HttpContext property, like this: If the controller method you’re testing uses anything from the HttpContext, then you’ll want to swap in your own value. Otherwise HttpContext will be null and you’ll get a NullReferenceException. Fortunately Microsoft … Read more

C# – The nameof() operator

The nameof() operator outputs the name of the class/method/property/type passed into it. Here’s an example: Note: nameof() was added in C# 6. nameof() eliminates duplication The DRY principle – Don’t Repeat Yourself – warns us against having duplication in the code. Whenever information or code is duplicated, it’s possible to change something in one spot … Read more

CA1062: Validate parameter is non-null before using it

When you have a public method that isn’t null checking its parameters, then you’ll get the CA1062 code analysis warning. This is part of the Nullable Reference Types feature. For example, the following code isn’t null checking the movieRepository parameter: This results in the CA1062 code analysis warning: CA1062 In externally visible method ‘void StreamingService.LogMovies(MovieRepository … Read more

C# – Merge two dictionaries in-place

When you merge two dictionaries, you can either merge them in-place, or create a new dictionary and copy the values over to it. The following extension method does an in-place merge of two dictionaries. It loops through items in the right dictionary, adding them to the left dictionary. When duplicate keys exist, it’s keeping the … Read more

C# – Check if a nullable bool is true

You can’t use nullable bools (bool?) exactly like regular bools, because they aren’t the same thing. When you try to use them like regular bools, you run into compiler errors and runtime exceptions. Instead, you have to explicitly compare the nullable bool with true/false. Here’s an example of checking if a nullable bool is true … 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# – 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# – Using custom attributes

Attributes are used to store additional info about a class/method/property. The attributes are read at runtime and used to change the program’s behavior. Here are a few examples of commonly used built-in attributes: In general, you should try to use built-in attributes when possible. When it makes sense, you can create your own custom attribute. … Read more