0

I am learning about LanguageExt and using functional programming styles in C#. I have created a new class, with my goal being a ValueObject:

public sealed class AlertDefinition : NewType<AlertDefinition, AlertDefinitionType>
{
    private AlertDefinition(AlertDefinitionType value) : base(value)
    {
    }

    public static Validation<Error, AlertDefinition> Create(AlertDefinitionType alertDefinitionType) =>
        (AllAlertDefinitionTypeValidator(alertDefinitionType))
            .Map(adt => new AlertDefinition(adt));
}

and where my validator is:

public static Validation<Error, AlertDefinitionType> AllAlertDefinitionTypeValidator(AlertDefinitionType alertDefinitionType) =>
        Enum.IsDefined(typeof(AlertDefinitionType), alertDefinitionType)
            ? Success<Error, AlertDefinitionType>(alertDefinitionType)
            : Fail<Error, AlertDefinitionType>(Error.New($"The value {alertDefinitionType} is not a valid {nameof(AlertDefinitionType)}"));

AlertDefinitionType is just an enum and I need to make certain that integers passed in a REST endpoint are valid against the enum.

Several things are tripping me up:

  1. Is this a good pattern for creating value objects in a functional way?
  2. How do I extract the AlertDefinitionType value from my AlertDefinition object? I've seen references .Match, but is it necessary every time or is there an easier way?
TortillaCurtain
  • 501
  • 4
  • 18

1 Answers1

0

This link helped me after the fact:

https://github.com/louthy/language-ext/issues/231

I was getting thrown by the fact that when retrieving a value I was getting either a Unit or a Validation<Error, AlertDefinition> type when all I wanted was the AlertDefinitionType value. This appears to give me what I want:

var x = myAlertDefinition.Match(
            Succ: definition => definition.Value,
            Fail: _ => (AlertDefinitionType)0);

The cast on the Fail seems a bit ugly, so if anyone has a better idea, I'm all ears.

TortillaCurtain
  • 501
  • 4
  • 18