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
EasyCreate a method named getSafeValue that takes two arguments:
- A nullable integer (
int?value) - An integer (
intdefaultValue)
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
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety