Using the Null-conditional Operator in C#
📖 Scenario: Imagine you are building a simple contact list app. Each contact may or may not have a phone number. You want to safely check if a contact has a phone number without causing errors if the phone number is missing.
🎯 Goal: Learn how to use the null-conditional operator (?.) in C# to safely access properties that might be null.
📋 What You'll Learn
Create a class called
Contact with a string property PhoneNumber that can be null.Create a variable called
contact and assign it a new Contact object with no phone number.Use the null-conditional operator
?. to safely get the length of the phone number string.Print the length or
null if the phone number is missing.💡 Why This Matters
🌍 Real World
In real apps, data can be missing or optional. The null-conditional operator helps avoid errors when accessing such data.
💼 Career
Understanding null safety is important for writing robust C# code, especially when working with APIs or databases where data might be missing.
Progress0 / 4 steps