-
Notifications
You must be signed in to change notification settings - Fork 46
/
Maybe.cs
57 lines (49 loc) · 1.36 KB
/
Maybe.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
using System.Collections.Generic;
namespace Kontur.Courses.Git
{
public class Maybe<T>
{
public static implicit operator Maybe<T>(T value)
{
return new Maybe<T>(value, null, true);
}
public static Maybe<T> FromError(string errorFormat, params object[] args)
{
return new Maybe<T>(default(T), string.Format(errorFormat, args), false);
}
private Maybe(T value, string error, bool hasValue)
{
Value = value;
Error = error;
HasValue = hasValue;
}
public override string ToString()
{
return HasValue ? Value.ToString() : "Error: " + Error;
}
protected bool Equals(Maybe<T> other)
{
return EqualityComparer<T>.Default.Equals(Value, other.Value) && string.Equals(Error, other.Error) && HasValue.Equals(other.HasValue);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Maybe<T>) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = EqualityComparer<T>.Default.GetHashCode(Value);
hashCode = (hashCode*397) ^ (Error != null ? Error.GetHashCode() : 0);
hashCode = (hashCode*397) ^ HasValue.GetHashCode();
return hashCode;
}
}
public readonly T Value;
public readonly string Error;
public readonly bool HasValue;
}
}