0
0
C Sharp (C#)programming~15 mins

Null-conditional operator in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the Contact class and a contact with no phone number
Create a class called Contact with a public string property PhoneNumber that can be null. Then create a variable called contact and assign it a new Contact object with PhoneNumber set to null.
C Sharp (C#)
Need a hint?

Use string? to allow PhoneNumber to be null.

2
Create a variable to hold the phone number length safely
Create an integer variable called phoneLength and assign it the length of contact.PhoneNumber using the null-conditional operator ?.. Use the null-coalescing operator ?? to assign 0 if the phone number is null.
C Sharp (C#)
Need a hint?

Use contact.PhoneNumber?.Length to get length safely, then ?? 0 to default to zero.

3
Change the contact to have a phone number
Change the contact variable so that PhoneNumber is set to the string "123-4567" instead of null.
C Sharp (C#)
Need a hint?

Assign the string "123-4567" to PhoneNumber.

4
Print the phone number length
Write a Console.WriteLine statement to print the value of phoneLength.
C Sharp (C#)
Need a hint?

Use Console.WriteLine(phoneLength); to show the length.