C# 6 null check

Like nullable types, null-conditional operators can be used now. Just put a ‘?’ (question mark) after the instance before calling the property on top of it. You don’t have to write additional if statements to check for null now. For example, let’s see a simple if condition which we will then see with the null-conditional operator in C# 6.0:

C# 6.0 - Simple Condition (www.kunal-chowdhury.com)[3].png

C# 6.0 - Nested Conditions (www.kunal-chowdhury.com)[3].png

Now let’s see, how it can be used to return a default value if the condition does not satisfy at all. In the below code snippet, you can see that “??” conditional operator can be used along with the null-conditional operator to return a value. In this case, if either of emp (employee object) or MemberOfGroups value is null, it will return –1:

C# 6.0 - Default Values in Conditions (www.kunal-chowdhury.com)[3].png

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s