简体   繁体   中英

Equivalent to Java's Optional.orElse in 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"

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 ?? operator .

string x = null;
Console.WriteLine(x ?? "NeedToCheckforNull");

I've created my own.

public class Optional<T> {
    private T value;
    public bool IsPresent { get; private set; } = false;

    private Optional() { }

    public static Optional<T> Empty() {
        return new Optional<T>();
    }

    public static Optional<T> Of(T value) {
        Optional<T> obj = new Optional<T>();
        obj.Set(value);
        return obj;
    }

    public void Set(T value) {
        this.value = value;
        IsPresent = true;
    }

    public T Get() {
        return value;
    }
}

考虑使用语言扩展选项类型

int x = optional.IfNone("NeedToCheckforNull");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM