Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Null-conditional operator in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Null-Conditional Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of null-conditional operator with null object
What is the output of this C# code snippet using the null-conditional operator?
C Sharp (C#)
class Program {
    static void Main() {
        string? text = null;
        int? length = text?.Length;
        System.Console.WriteLine(length == null ? "null" : length.ToString());
    }
}
Anull
BThrows NullReferenceException
C0
DEmpty string
Attempts:
2 left
💡 Hint
The null-conditional operator returns null if the object is null instead of throwing an exception.
❓ Predict Output
intermediate
2:00remaining
Null-conditional operator with method invocation
What will this C# program print?
C Sharp (C#)
class Program {
    static string? GetName(bool returnNull) {
        if (returnNull) return null;
        return "Alice";
    }
    static void Main() {
        string? name = GetName(true);
        int? length = name?.Length;
        System.Console.WriteLine(length ?? -1);
    }
}
AThrows NullReferenceException
B5
Cnull
D-1
Attempts:
2 left
💡 Hint
The null-coalescing operator '??' provides a default value if the left side is null.
🔧 Debug
advanced
2:00remaining
Identify the error with null-conditional operator usage
What error does this C# code produce?
C Sharp (C#)
class Program {
    static void Main() {
        string? text = null;
        int length = text?.Length;
        System.Console.WriteLine(length);
    }
}
ANullReferenceException at runtime
BSyntax error: missing semicolon
CCannot implicitly convert type 'int?' to 'int'
DNo error, prints 0
Attempts:
2 left
💡 Hint
The null-conditional operator returns a nullable type, but the variable is non-nullable.
🧠 Conceptual
advanced
2:00remaining
Behavior of null-conditional operator with events
Consider this C# code snippet. What is the purpose of using the null-conditional operator when invoking the event?
C Sharp (C#)
public class Publisher {
    public event System.Action? OnChange;
    public void Raise() {
        OnChange?.Invoke();
    }
}
AIt unsubscribes all event handlers before invoking.
BIt prevents a NullReferenceException if no subscribers are attached to the event.
CIt forces the event to always have at least one subscriber.
DIt throws an exception if the event has no subscribers.
Attempts:
2 left
💡 Hint
Events can be null if no methods are subscribed.
❓ Predict Output
expert
2:00remaining
Output with chained null-conditional operators and null-coalescing
What is the output of this C# program?
C Sharp (C#)
class Person {
    public string? Name { get; set; }
    public Person? Friend { get; set; }
}
class Program {
    static void Main() {
        Person? p = new Person { Name = "Bob", Friend = null };
        string friendName = p?.Friend?.Name ?? "No friend";
        System.Console.WriteLine(friendName);
    }
}
ANo friend
BBob
Cnull
DThrows NullReferenceException
Attempts:
2 left
💡 Hint
The null-conditional operator returns null if any part of the chain is null, then the null-coalescing operator provides a default.

Practice

(1/5)
1. What does the null-conditional operator ?. do in C#?
easy
A. It safely accesses a member only if the object is not null, otherwise returns null.
B. It throws an exception if the object is null.
C. It converts a null object to an empty string.
D. It forces the object to be non-null.

Solution

  1. Step 1: Understand the purpose of the null-conditional operator

    The operator ?. is used to access members of an object only if the object is not null.
  2. Step 2: Behavior when object is null

    If the object is null, instead of throwing an exception, it returns null safely.
  3. Final Answer:

    It safely accesses a member only if the object is not null, otherwise returns null. -> Option A
  4. Quick Check:

    Null-conditional operator = safe member access [OK]
Hint: Remember: ?. returns null instead of error if object is null [OK]
Common Mistakes:
  • Thinking it throws an exception on null
  • Confusing it with null-coalescing operator
  • Assuming it converts null to empty string
2. Which of the following is the correct syntax to safely access the Length property of a string variable text that might be null?
easy
A. int length = text.Length?;
B. int? length = text?.Length;
C. int length = text?.Length;
D. int? length = text.Length?.;

Solution

  1. Step 1: Identify correct null-conditional syntax

    The null-conditional operator is ?. placed before the member name, like text?.Length.
  2. Step 2: Match variable type with possible null

    Since text might be null, the result text?.Length is nullable, so use int? to hold it.
  3. Final Answer:

    int? length = text?.Length; -> Option B
  4. Quick Check:

    Correct syntax = int? length = text?.Length; [OK]
Hint: Use int? for nullable results with ?. operator [OK]
Common Mistakes:
  • Placing ? after Length instead of before
  • Using non-nullable int for nullable result
  • Adding extra dots or question marks
3. What is the output of the following code?
string? name = null;
int? length = name?.Length;
Console.WriteLine(length == null ? "Null" : length.ToString());
medium
A. Null
B. Empty string
C. Throws NullReferenceException
D. 0

Solution

  1. Step 1: Evaluate null-conditional operator on null string

    The variable name is null, so name?.Length returns null safely.
  2. Step 2: Check output logic

    The code prints "Null" if length is null, otherwise prints the length. Since length is null, it prints "Null".
  3. Final Answer:

    Null -> Option A
  4. Quick Check:

    Null string length = null, prints "Null" [OK]
Hint: ?. returns null for null object, so output is "Null" [OK]
Common Mistakes:
  • Expecting 0 instead of null
  • Thinking it throws exception
  • Confusing null with empty string
4. Identify the error in this code snippet:
Person? person = null;
int age = person?.Age;
Console.WriteLine(age);
medium
A. Missing semicolon after Console.WriteLine.
B. Null-conditional operator cannot be used on objects.
C. Cannot assign nullable int to non-nullable int without cast.
D. Person class must be non-nullable.

Solution

  1. Step 1: Analyze the type of person?.Age

    The expression person?.Age returns int? (nullable int) because person might be null.
  2. Step 2: Check assignment compatibility

    Variable age is declared as int (non-nullable), so assigning int? to int without conversion causes a compile error.
  3. Final Answer:

    Cannot assign nullable int to non-nullable int without cast. -> Option C
  4. Quick Check:

    Nullable to non-nullable assignment needs cast [OK]
Hint: Nullable result needs nullable variable or cast [OK]
Common Mistakes:
  • Ignoring nullable type returned by ?. operator
  • Assuming no error on assignment
  • Thinking null-conditional operator is invalid here
5. Given a list of Person objects where some may be null, how can you safely get a List<int> of their ages (with 0 for null persons) using the null-conditional operator?
List<Person?> people = new() { new Person(30), null, new Person(25) };
var ages = ???;

Choose the correct code to replace ???.
hard
A. people.Select(p => p?.Age).ToList();
B. people.Select(p => p.Age).ToList();
C. people.Select(p => p.Age ?? 0).ToList();
D. people.Select(p => p?.Age ?? 0).ToList();

Solution

  1. Step 1: Understand the list and nulls

    The list contains Person? objects, some are null, so accessing Age needs safe access.
  2. Step 2: Use null-conditional with fallback

    p?.Age safely accesses Age or returns null; using ?? 0 replaces null ages with 0 to avoid nullable list.
  3. Step 3: Check other options

    people.Select(p => p?.Age).ToList(); returns nullable ints, people.Select(p => p.Age).ToList(); throws exception on null, people.Select(p => p.Age ?? 0).ToList(); is invalid because p can be null.
  4. Final Answer:

    people.Select(p => p?.Age ?? 0).ToList(); -> Option D
  5. Quick Check:

    Safe access with fallback = people.Select(p => p?.Age ?? 0).ToList(); [OK]
Hint: Use ?. with ?? to handle nulls and provide default [OK]
Common Mistakes:
  • Not handling null Person objects
  • Forgetting to provide fallback value
  • Assuming Select handles nulls automatically
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard