-
Notifications
You must be signed in to change notification settings - Fork 1
/
Optional.cs
61 lines (50 loc) · 987 Bytes
/
Optional.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Diagnostics;
using System.Reflection;
public class Optional<T>
{
private bool _isPresent = false;
private T _value;
private Optional()
{
}
private Optional(T value)
{
this._value = value;
_isPresent = true;
}
public static Optional<T> Of(T value)
{
return new Optional<T>(value);
}
public static Optional<T> Empty()
{
return new Optional<T>();
}
public T GetValue()
{
if (!_isPresent)
{
throw new NoValueException("Optional doesn't contain a value.");
}
else
{
return _value;
}
}
public T OrElse(T value)
{
return _isPresent ? this._value : value;
}
public bool IsPresent()
{
return _isPresent;
}
public void IfPresent(Action<T> action)
{
if (_isPresent)
{
action(this._value);
}
}
}