Menu
Coddy logo textTech

Conditional Logical Operators

Part of the Logic & Flow section of Coddy's C# journey — lesson 37 of 66.

Conditional logical operators in C# provide a way to combine conditions with special behaviors. The two main conditional logical operators are ?? (null-coalescing) and ?. (null-conditional).

Let's first explore the null-coalescing operator (??). This operator returns the left-hand operand if it is not null, otherwise it returns the right-hand operand.

Create a string variable that might be null:

string name = null;

Use the null-coalescing operator to provide a default value:

string displayName = name ?? "Guest";

After executing the above code, the variable displayName contains:

"Guest"

If name had a value, that value would be used instead:

string name = "Alice";
string displayName = name ?? "Guest";

Now displayName contains:

"Alice"
challenge icon

Challenge

Easy

Create a method named getSafeValue that takes two arguments:

  • A nullable integer (int? value)
  • An integer (int defaultValue)

The method should return the value if it's not null, otherwise it should return the defaultValue. Use the null-coalescing operator (??) to achieve this.

Cheat sheet

The null-coalescing operator (??) returns the left-hand operand if it is not null, otherwise it returns the right-hand operand:

string name = null;
string displayName = name ?? "Guest"; // Returns "Guest"
string name = "Alice";
string displayName = name ?? "Guest"; // Returns "Alice"

The null-conditional operator (?.) allows safe access to members of an object that might be null.

Try it yourself

using System;

class GetSafeValue
{
    public static int getSafeValue(int? value, int defaultValue)
    {
        // Write your code here
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow