Null pointer exceptions are no fun. You can avoid them and keep your code clean and maintainable by using these techniques to elegantly handle null values in C#. Credit: Lucadp / Getty Images When working on applications in any programming language, you might have encountered null exceptions or null reference exceptions. A null pointer or a null reference is one that does not refer to a valid memory location or object. It is a problem that has plagued programmers as long as programmers have been writing programs. A null value is a special value that denotes non-availability of a valid value. A null value is one that, when assigned to an object, resets the value of a field or a variable in the object to no value, i.e. an empty value. You must handle null values in your application’s code to avoid null reference exceptions and unexpected behavior of your application at runtime. In this article, we’ll examine various ways to deal with null values in C#. To work with the code examples provided below, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here. Create a console application project in Visual Studio First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2022 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Click Next. In the “Additional information” window shown next, choose “.NET 7.0 (Standard Term Support)” as the Framework version you want to use. Click Create. We’ll use this .NET 7 console application project to work with null values in the subsequent sections of this article. We’ll examine five ways to handle null values in C#. The one you should use will depend on the requirements of your application. Null-conditional operator (?.) in C# When an object is not null, you can access its members (data members and methods) using the null-conditional operator (?.). If the object is null, the null-conditional operator will return null but will not throw a runtime exception when accessing the members of the object. Consider the following class. public class Author { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } } Now write the following code to create an Author, assign values to the FirstName and LastName properties, and get the length of the Address property. Note that we have not assigned a value to the Address property, so it is set to null. Author author = new Author(); author.FirstName = "Joydip"; author.LastName = "Kanjilal"; int length = author.Address.Length; When the preceding code snippet is executed, you will encounter a runtime exception as shown in Figure 1 below. IDG Figure 1. Oops, a null reference exception. The following code example shows how you can use the null-conditional operator in C# to avoid the runtime exception. Author author = new Author(); author.FirstName = "Joydip"; author.LastName = "Kanjilal"; author.Address = null; int? length = author.Address?.Length; Null-coalescing assignment operator (??=) in C# In the event that the value of the left-hand operand is null, the null-coalescing operator (??=) will set the value of the right-hand operand of an expression to the operand present at the left-hand side. Here is an example of how this operator can be used in C#: Author author = new Author(); author.FirstName = "Joydip"; author.LastName = "Kanjilal"; author.Address = null; author.Address ??= "Default"; Console.WriteLine(author.Address); Null-forgiving operator (!.) in C# The null-forgiving or null-suppression operator (!.) allows you to suppress all warnings in an expression. You should use this operator only if you are sure that the value of a property or an object will not be null, and you want to suppress warnings in your application’s code that you know are incorrect. The following code snippet illustrates how the null-forgiving operator can be used. Author author = new Author(); author.FirstName = "Joydip"; author.LastName = "Kanjilal"; author.Address = null!; int length = author.Address.Length; Console.WriteLine(length); Conditional operator (?:) in C# You can use the conditional operator (?:) to evaluate an expression that includes a null value in one of the two operands. The conditional operator is also known as the ternary conditional operator, because the statements that use this operator have three parts: a condition (a Boolean expression), a consquent expression, and an alternative expression. The consequent expression (at the left-hand side of the :) is evaluated/returned if the condition evaluates true. The alternative expression (at the right-hand side of the :) is evaluated/returned if the condition evaluates false. Here is an example that illustrates how the conditional operator can be used in an expression to handle null values: Author author = new Author(); author.FirstName = "Joydip"; author.LastName = "Kanjilal"; author.Address = null!; string result = (author.Address != null) ? author.Address : "Unknown"; Console.WriteLine(result); The is operator in C# You can also use the is keyword to check if a value is null. This operator (is is a keyword and also works as an operator) can be used to compare constant values and even null values. The following code snippet shows how you can use this operator in C# to handle null values. Author author = new Author(); author.FirstName = "Joydip"; author.LastName = "Kanjilal"; author.Address = null!; if(author.Address != null) { Console.WriteLine(author.Address); } else { Console.WriteLine("The value of the Address property is null"); } In addition to the five techniques shown in this article, you can check for null values by using the == operator in C#. The primary goal of using the operators demonstrated here to handle null values is to avoid having to write code to handle exceptions. You can keep your code clean and manageable using the techniques shown here. Related content news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks how-to How to use DispatchProxy for AOP in .NET Core Take advantage of the DispatchProxy class in C# to implement aspect-oriented programming by creating proxies that dynamically intercept method calls. By Joydip Kanjilal Nov 14, 2024 7 mins Microsoft .NET C# Development Libraries and Frameworks news Microsoft’s .NET 9 arrives, with performance, cloud, and AI boosts Cloud-native apps, AI-enabled apps, ASP.NET Core, Aspire, Blazor, MAUI, C#, and F# all get boosts with the latest major rev of the .NET platform. By Paul Krill Nov 12, 2024 4 mins C# Generative AI Microsoft .NET feature Can Wasm replace containers? WebAssembly revolutionized browser apps, and promises to upend the server stack. How will it impact containers and Kubernetes? Six experts weigh in. By Bill Doerrfeld Nov 11, 2024 12 mins Containers Kubernetes Cloud Native Resources Videos