Back to blog
Jul 2021·1 min readAI-translated

The Null-Conditional Operator

#allgemein

The "null-conditional operator" is a feature introduced with C# 6.0 that lets developers handle null values more safely. It is a simple operator that acts as an optional member access operator, which only evaluates if the object is not null.

Let me give you an example: imagine you have a class called "Person" that has a name and an address. If you now want to access a person's address, you normally have to make sure the person is not null before accessing the address.

With the "null-conditional operator", however, you can skip that check and access the address directly if the person exists. If it is null, the operator returns null and the code isn't evaluated any further, which avoids potential NullReferenceException errors.

Here is some example code to illustrate:

Person person = GetPerson();

// Normally you'd have to check that the person is not null before accessing the address
if (person != null)
{
    Address address = person.Address;
}

// With the null-conditional operator you can access the address directly without causing a NullReferenceException
Address address = person?.Address;

As you can see, using the "null-conditional operator" is much easier and safer for avoiding null references in C#.

Another advantage of this feature is that it makes the code more readable, since it reduces the need for additional null checks. That makes the code shorter and easier to understand.

All in all, the "null-conditional operator" is a great feature that helps developers handle null values more safely and effectively. So if you're a C# developer, you should definitely try it out.

I hope this post helped you get to know the "null-conditional operator" and showed you how it can help you code more safely and efficiently. If you have further questions, don't hesitate to ask them in the comments!

NewerJavaScript Object Notation with SQLOlderValidating Email Addresses