Equivalent to Java's Optional.orElse in C#
You can use the ??
operator.
Your code will be updated to:
string x = null;
string y = x ?? "NeedToCheckforNull";
See: ?? Operator (C# Reference)
C# has the special Nullable<T>
type which can be declared with int?
, decimal?
, etc. These can provide a default value by using .GetValueOrDefault()
, T GetValueOrDefault(T defaultValue)
, and the ??
opterator.
string x = null;
Console.WriteLine(x ?? "NeedToCheckforNull");