In C#, conditional operators provide powerful ways to write concise and readable code. Today, we’ll explore several such operators: the ternary conditional (?:), null-coalescing (??), null-coalescing assignment (??=), null-conditional (?. and ?[]), null-conditional delegate invocation (?.()), the nameof operator and the ! operator that has double usage.

The Ternary Conditional Operator (?:)

The ternary conditional operator (?:) is a compact way to perform basic conditional logic. It works as a shorthand for if-else statements, returning one value if a condition is true and another if it is false.

Syntax:

condition ? trueResult : falseResult

Example:

int age = 20;
string result = age >= 18 ? "Adult" : "Minor";
Console.WriteLine(result); // Outputs: Adult

The Null-Coalescing Operator (??)

The null-coalescing operator (??) is used to provide a default value when dealing with null references. It returns the left-hand operand if it is not null; otherwise, it returns the right-hand operand.

Syntax:

takeThisIfThisIsNotNull ?? ElseTakeThis

Example:

string input = null;
string result = input ?? "Default Value";
Console.WriteLine(result); // Outputs: Default Value

The Null-Coalescing Assignment Operator (??=)

Introduced in C# 8.0, the null-coalescing assignment operator (??=) is used to assign a value to a variable only if that variable is null. It’s a shorthand for checking if a variable is null and then assigning a value to it.

Syntax:

ifThisIsNullThenAssignTheValue ??= value

Example:

List<int> numbers = null;
numbers ??= new List<int>();
numbers.Add(1);
Console.WriteLine(numbers.Count); // Outputs: 1

The Null-Conditional Operator (?. and ?[])

The null-conditional operator (?. and ?[]) allows you to safely access members or elements of an object that might be null. It short-circuits and returns null if the operand is null, preventing NullReferenceException.

Syntax:

object?.Member //get the value of the property or null
array?[index] //get the value of the array or null

Example:

User user = null;
string name = user?.Name;
Console.WriteLine(name); // Outputs: (null)

int[] numbers = null;
int? firstNumber = numbers?[0];
Console.WriteLine(firstNumber); // Outputs: (null)

The nameof Operator

The nameof operator returns the name of a variable, type, or member as a string. It’s particularly useful for refactoring and avoiding magic strings in code.

Syntax:

nameof(member)

Example:

public void LogError(string message, string paramName)
{
    Console.WriteLine($"Error in {paramName}: {message}");
}

string param = "username";
LogError("Value cannot be null", nameof(param));

Logical NOT Operator or Null Forgiving Operator

The ! operator inverts the value of a boolean expression.

The ! operator can also be used to assert that a variable is not null, telling the compiler to suppress any nullability warnings.

Syntax:

!isSmart
student!.Name //removes the compiler warning

Example:

bool isRaining = true;
if (!isRaining)
{
    Console.WriteLine("It's not raining.");
}
else
{
    Console.WriteLine("It's raining.");
}
// Outputs: It's raining.

------------------------------------------------------

#nullable enable

string? nullableString = GetNullableString();
Console.WriteLine(nullableString!.Length);

string? GetNullableString()
{
    return "Hello, World!";
}

Conclusion

Understanding and utilizing the ?:, ??, ??=, ?., ?.(), nameof and ! operators can greatly enhance the clarity of your code. They allow you to handle conditional logic and null values more elegantly, making your code cleaner and more maintainable.

Affiliate promo

If you love learning new stuff and want to support me, consider buying a course from Dometrain using this link: Browse courses – Dometrain. Thank you!

Leave a comment

Trending