8

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"

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Ryan Leach
  • 3,926
  • 3
  • 29
  • 61

4 Answers4

11

You can use the ?? operator.

Your code will be updated to:

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

See: ?? Operator (C# Reference)

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
d.moncada
  • 16,032
  • 4
  • 49
  • 76
4

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");
granadaCoder
  • 23,729
  • 8
  • 95
  • 129
0

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;
    }
}
SM Adnan
  • 537
  • 2
  • 9
  • 1
    may I suggest you use a struct to provide that instead of a class – jalsh Jul 26 '20 at 15:26
  • As it is mutable, I prefer using class. – SM Adnan Jul 27 '20 at 11:07
  • Another reason of not using struct is it can contain data of larger than 16 bytes. Reference: https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct – SM Adnan Jul 27 '20 at 11:07
  • 2
    Optional should be immutable, the doc you're referencing discourages the use of struct when it has *all* the mentioned characteristics, so the fact that it's not larger than 16 bytes doesn't change it. Optional should be a sturct, just like Nullable is – jalsh Sep 18 '20 at 03:46
0

consider using language extensions option type

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

Elazar Neeman
  • 111
  • 1
  • 3