Skip to content

Instantly share code, notes, and snippets.

@mausch
Created April 25, 2020 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mausch/87a0a698a4cc647da1487abc13c2f352 to your computer and use it in GitHub Desktop.
Save mausch/87a0a698a4cc647da1487abc13c2f352 to your computer and use it in GitHub Desktop.
newtypes in C#
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