I'm looking for nice syntax for providing a default value in the case of null. I've been used to using Optional's instead of null in Java where API's are concerned, and was wondering if C#'s nicer nullable types have an equivalent?
Optionals
Optional<String> x = Optional<String>.absent();
String y = x.orElse("NeedToCheckforNull"); //y = NeedToCheckforNull
@nullable
String x = null;
String y = x == null ? "NeedToCheckforNull" : x ; //y = NeedToCheckforNull
How would I make the above more readable in C#?
JavaScript would allow y = x | "NeedToCheckforNull"
What is the orElse() method of the Optional class? The orElse() method will return the value present in an Optional object. If the value is not present, then the passed argument is returned.
orElse(): returns the value if present, otherwise returns other. orElseGet(): returns the value if present, otherwise invokes other and returns the result of its invocation.
isPresent() method returns true if the Optional contains a non-null value, otherwise it returns false. ifPresent() method allows you to pass a Consumer function that is executed if a value is present inside the Optional object. It does nothing if the Optional is empty.
An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value. The else statement is an optional statement and there could be at most only one else statement following if.
You can use the ??
operator.
Your code will be updated to:
string x = null;
string y = x ?? "NeedToCheckforNull";
See: ?? Operator (C# Reference)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With