Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent to Java's Optional.orElse in C#

Tags:

java

c#

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"

like image 840
Ryan Leach Avatar asked Sep 01 '17 03:09

Ryan Leach


People also ask

What is orElse in optional?

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.

What is the difference between orElse and orElseGet?

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.

What is difference between isPresent and ifPresent?

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.

Is else optional in if statement?

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.


1 Answers

You can use the ?? operator.

Your code will be updated to:

string x = null;
string y = x ?? "NeedToCheckforNull"; 

See: ?? Operator (C# Reference)

like image 60
d.moncada Avatar answered Oct 04 '22 07:10

d.moncada