I made this class to cover identical needs:
public class NamedInt : IComparable<int>, IEquatable<int>
{
internal int Value { get; }
protected NamedInt() { }
protected NamedInt(int val) { Value = val; }
protected NamedInt(string val) { Value = Convert.ToInt32(val); }
public static implicit operator int (NamedInt val) { return val.Value; }
public static bool operator ==(NamedInt a, int b) { return a?.Value == b; }
public static bool operator ==(NamedInt a, NamedInt b) { return a?.Value == b?.Value; }
public static bool operator !=(NamedInt a, int b) { return !(a==b); }
public static bool operator !=(NamedInt a, NamedInt b) { return !(a==b); }
public bool Equals(int other) { return Equals(new NamedInt(other)); }
public override bool Equals(object other) {
if ((other.GetType() != GetType() && other.GetType() != typeof(string))) return false;
return Equals(new NamedInt(other.ToString()));
}
private bool Equals(NamedInt other) {
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(Value, other.Value);
}
public int CompareTo(int other) { return Value - other; }
public int CompareTo(NamedInt other) { return Value - other.Value; }
public override int GetHashCode() { return Value.GetHashCode(); }
public override string ToString() { return Value.ToString(); }
}
And to consume it in your case:
public class BuyOffer: NamedInt {
public BuyOffer(int value) : base(value) { }
public static implicit operator BuyOffer(int value) { return new BuyOffer(value); }
}
public class SellOffer: NamedInt {
public SellOffer(int value) : base(value) { }
public static implicit operator SellOffer(int value) { return new SellOffer(value); }
}
If you need to be able to serialize it (Newtonsoft.Json), let me know and I'll add the code.
int
, because if they did, then a valid operation would be to assign one to the other! (Since anint
can be assigned to anint
.) You need to be more precise what operations you want to allow and set up the striut to allow exactly those operations. – Quirk