Getting a value from an Option without 'Some' in value #1142
-
I have a function that takes in two public static Validation<Error, bool> ValidateDateRange(Option<DateTime> startDateTime,
Option<DateTime> endDateTime)
{
var result = map(Tuple(startDateTime, endDateTime), (start, end) => (start.IsNone || end.IsNone) || start <= end);
return result
? Success<Error, bool>(result)
: Fail<Error, bool>(Error.New($"The value of the start date '{startDateTime.GetValue()}' cannot be greater than the end date '{endDateTime.GetValue()}'."));
} As you can see, I created an extension method called public static class GetValues
{
public static string? GetValue<T>(this Option<T> input) =>
input.Match(
Some: x => x!.ToString(),
None: () => string.Empty);
} My goal is to include the value of the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Not sure if I'm entirely parsing what you're asking, but I think there's an alternative route that's more elegant. Really you want to work with the public static Error InvalidRange(DateTime s, DateTime e) =>
Error.New($"The value of the start date '{s}' cannot be greater than the end date '{e}'.");
public static Validation<Error, Unit> ValidateDateRange(
Option<DateTime> startDateTime,
Option<DateTime> endDateTime) =>
(startDateTime.Case, endDateTime.Case) switch
{
(DateTime s, DateTime e) when s > e => InvalidRange(s, e),
_ => Success<Error, Unit>(unit),
}; What this does is it pattern-matches the I have also changed it to return This test: System.Console.WriteLine(ValidateDateRange(DateTime.Now, DateTime.Now.AddDays(1)));
System.Console.WriteLine(ValidateDateRange(DateTime.Now, DateTime.Now.AddDays(-1)));
System.Console.WriteLine(ValidateDateRange(None, DateTime.Now));
System.Console.WriteLine(ValidateDateRange(DateTime.Now, None)); Yields: Success(())
Fail([The value of the start date '15/11/2022 17:17:04' cannot be greater than the end date '14/11/2022 17:17:04'.])
Success(())
Success(()) |
Beta Was this translation helpful? Give feedback.
Not sure if I'm entirely parsing what you're asking, but I think there's an alternative route that's more elegant. Really you want to work with the
Some
state when you know it is aSome
state, not try to hack it to be either the value or an empty string after-the-fact: