In C# it is a common and popular pattern to use strongly typed entity IDs instead of using integers or the likes for IDs on your entities. Strongly typed entity IDs is a great help when trying to prevent you from mixing an Order ID with an OrderLine ID.<\/p>\n\n\n\n
Andrew Lock recently wrote a series<\/a> on the topic that you should go read now.<\/p>\n\n\n\n A strongly typed entity ID may look something like this (the example used by Andrew Lock):<\/p>\n\n\n\n That is a lot of code to write for every ID in your domain model and you should create a code snippet in Visual Studio to do it. However, as with many things you get this more or less for free in F# with single case union types<\/a>. All it takes is this:<\/p>\n\n\n\n F# will give to equal operators and the other stuff for free, hence:<\/p>\n\n\n\npublic readonly struct OrderId : IComparable<OrderId>, IEquatable<OrderId>\n{\n public int Value { get; }\n\n public OrderId(int value)\n {\n Value = value;\n }\n\n public bool Equals(OrderId other) => this.Value.Equals(other.Value);\n public int CompareTo(OrderId other) => Value.CompareTo(other.Value);\n\n public override bool Equals(object obj)\n {\n if (ReferenceEquals(null, obj)) return false;\n return obj is OrderId other && Equals(other);\n }\n\n public override int GetHashCode() => Value.GetHashCode();\n public override string ToString() => Value.ToString();\n\n public static bool operator ==(OrderId a, OrderId b) => a.CompareTo(b) == 0;\n public static bool operator !=(OrderId a, OrderId b) => !(a == b);\n}\n<\/code><\/pre>\n\n\n\n
type CarID = CarID of int<\/code><\/pre>\n\n\n\n
let id1 = (CarID 42)\nlet id2 = (CarID 42)\n\nid1 = id2 \/\/ true<\/code><\/pre>\n\n\n\n