C# > Core C# > Operators and Expressions > Null-conditional Operator (?.)
Null-Conditional Operator with Indexers
This code snippet demonstrates how to use the null-conditional operator (?.) with indexers on a potentially null collection, preventing NullReferenceExceptions when accessing elements.
Code Example
The code initializes a `List
using System;
using System.Collections.Generic;
public class Example
{
public static void Main(string[] args)
{
List<string> names = null; // Or initialized with a List of strings
// Using the null-conditional operator with an indexer
string first_name = names?[0];
Console.WriteLine($"First Name: {first_name ?? \"No names available\"}");
}
}
Concepts Behind the Snippet
The null-conditional operator (?.) works seamlessly with indexers. This is particularly useful when working with collections (arrays, lists, dictionaries) that might be null or empty. It provides a concise way to safely access elements without the need for explicit null checks.
Real-Life Use Case
Imagine fetching a list of products from an external API. The API might return null if there are no products available. Using the null-conditional operator, you can safely access the first product in the list without the risk of a NullReferenceException, displaying a message like 'No products found' if the list is null or empty.
Best Practices
Use the null-conditional operator with indexers whenever dealing with collections that could potentially be null or empty. Combine it with null-coalescing operators (??) or conditional statements to handle empty collections gracefully. Avoid unnecessary uses when the collection is guaranteed to be initialized.
Interview Tip
Be prepared to demonstrate how to use the null-conditional operator with indexers. Be ready to discuss the advantages of this approach over traditional null checks and how it improves code readability and maintainability. Also, know how to handle empty collections when using indexers, as accessing an element at an invalid index (e.g., index 0 of an empty list) will still throw an exception (IndexOutOfRangeException) even with null-conditional operator in place. The null conditional operator will only prevent NullReferenceExceptions, not IndexOutOfRangeExceptions.
When to Use Them
Employ the null-conditional operator with indexers when you need to access elements of a collection that might be null. This is common when working with data from external sources, user input, or data transfer objects.
Alternatives
A traditional approach involves checking if the collection is null and then checking if it contains any elements before accessing an element by index: csharp string first_name; if (names != null && names.Count > 0) { first_name = names[0]; } else { first_name = null; // Or some default value } This is more verbose and requires additional checks compared to using the null-conditional operator.
Pros
Cons
FAQ
-
Does the null-conditional operator prevent IndexOutOfRangeExceptions?
No. The null-conditional operator only prevents NullReferenceExceptions. If the collection is not null but you try to access an index that's out of range, you'll still get an IndexOutOfRangeException. You will need to check if the index exist inside your array/list. -
Can I use the null-conditional operator with dictionaries?
Yes, you can use it with dictionaries to safely access values by key. For example: `string value = myDictionary?["key"];`