Created
April 25, 2020 22:40
-
-
Save mausch/87a0a698a4cc647da1487abc13c2f352 to your computer and use it in GitHub Desktop.
newtypes in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface IValue<out T> | |
{ | |
T Value { get; } | |
} | |
interface INewTypeEq<TSelf, TValue> : IValue<TValue>, IEquatable<TSelf> | |
where TValue : IEquatable<TValue> | |
where TSelf : INewTypeEq<TSelf, TValue> | |
{ | |
TSelf New(TValue value); | |
} | |
interface INewTypeComp<TSelf, TValue>: INewTypeEq<TSelf, TValue>, IComparable<TSelf> | |
where TValue: IEquatable<TValue>, IComparable<TValue> | |
where TSelf: INewTypeEq<TSelf, TValue>, INewTypeComp<TSelf, TValue> | |
{ | |
} | |
// add TypeConverter / JsonConverter attribute if necessary | |
struct UserId : INewTypeComp<UserId, Guid> | |
{ | |
public Guid Value { get; } | |
public UserId(Guid value) | |
{ | |
Value = value; | |
} | |
public UserId New(Guid value) => new UserId(value); | |
public bool Equals(UserId other) => Value.Equals(other.Value); | |
public override bool Equals(object obj) => obj is UserId other && Equals(other); | |
public int CompareTo(UserId other) => Value.CompareTo(other.Value); | |
public override int GetHashCode() => Value.GetHashCode(); | |
public override string ToString() => Value.ToString(); | |
public static bool operator > (UserId a, UserId b) => a.CompareTo(b) > 0; | |
public static bool operator < (UserId a, UserId b) => a.CompareTo(b) < 0; | |
public static bool operator <= (UserId a, UserId b) => a.CompareTo(b) <= 0; | |
public static bool operator >= (UserId a, UserId b) => a.CompareTo(b) >= 0; | |
public static bool operator == (UserId a, UserId b) => a.CompareTo(b) == 0; | |
public static bool operator != (UserId a, UserId b) => !(a == b); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment