C# Tip: Null-Conditional Operators

Juarez Júnior - Sep 18 - - Dev Community

Let’s talk about Null-Conditional Operators, introduced in C# 6, which allow you to check if an object is null before accessing its members, avoiding null reference exceptions concisely. See the example in the code below.

public class Product
{
    public string Name { get; set; }
    public decimal? Price { get; set; }
}

public class Program
{
    public static void Main()
    {
        Product product = null;
        // Using null-conditional operator to safely access members
        Console.WriteLine(product?.Name ?? "Product not specified");  // Output: Product not specified

        product = new Product { Name = "Pen", Price = 2.99m };
        Console.WriteLine(product?.Name);  // Output: Pen
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

Null-Conditional Operators are useful for simplifying code when accessing properties or methods of objects that might be null. By using ?. or ?[], you can check if an object is null before trying to access its members, avoiding the need for multiple if (obj != null) checks throughout the code.

This is especially useful in scenarios where there are many calls to properties or methods that could result in null objects, such as when working with APIs, database data, or collection manipulation. They make the code cleaner, easier to read, and less prone to null reference errors.

Source code: GitHub

I hope this tip helps you use Null-Conditional Operators to simplify your code and avoid errors! Until next time.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player