A month ago I asked that question about how to fulfill business rules with F# types.
The given answer worked well for me but when working with the type I struggled by comparing two instances of that type.
Here´s the implementation again:
[<AutoOpen>]
module JobId =
open System
type JobId = private JobId of string with
static member Create() = JobId(Guid.NewGuid().ToString("N"))
static member Create(id:Guid) =
if id = Guid.Empty then None
else Some(JobId(id.ToString("N")))
static member Create(id:string) =
try JobId.Create(Guid(id))
with :? FormatException -> None
[<Extension>]
type Extensions =
[<Extension>]
static member GetValue(jobId : JobId) : string =
match jobId with
| JobId.JobId id -> id
Because it´s used as an identifier I always have to compare two instances.
code in C#
IEnumerable<JobId> jobIds = await GetAllJobids();
JobId selectedJobId = GetSelectedJobId();
// that´s what I would like to do
if (jobIds.Any(id => id == selectedJobId))
{
...
}
// now I always have to compare the strings
if (jobIds.Any(id => id.GetValue() == selectedJobId.GetValue()))
{
...
}
I tried to override ==
operators but i couldn´t do it because the internal value is not just a simple field.
Is it possible to get to my wanted behavior? Thanks for your help!
F# unions are .NET sealed classes with implemented structural compare by default, but they don't overrite the '==' operators.
Check the representation of the F# classes in C# . You can see how the .Equal
method is implemented.
What you can do is
if (jobIds.Any(id => id.Equals(selectedJobId))) {}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.