Casting a Validation #1125
-
Is it possible to cast or convert a Validation that returns a subclass to a Validation that uses the base class? For example, if my function returns:
and I want to be able to pass it as:
Is this even possible? Do I need to extract the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Inheritance is obviously something that isn't used much in FP. However, we use it to represent discriminated unions - because there's no first class concept in C#. One thing I tend to do is write constructor functions that always return the base class, which makes casting less problematic. I'll then use pattern-matching to get at the derived-types. For example, if we create a simple public abstract record Colour;
public sealed record Red(int Amount) : Colour;
public sealed record Green(int Amount) : Colour;
public sealed record Blue(int Amount) : Colour; I would add constructors to public abstract record Colour
{
public static Colour Red(int amount) => new Red(amount);
public static Colour Green(int amount) => new Green(amount);
public static Colour Blue(int amount) => new Blue(amount);
} This then gives the feeling of a discriminated union in pretty much every way (other than the For example, a simple mapping: var mx = Some(Colour.Red(100));
var my = mx.Map(c => c switch
{
Red (var amount) => Colour.Green(amount),
Green(var amount) => Colour.Blue(amount),
Blue (var amount) => Colour.Red(amount)
}); This is pretty much how discriminated unions work in other languages, you never work with a type of If you absolutely must be able to cast between different sub and super types, then you can map: var mx = Some(new Red(100));
var my = mx.Map(static c => (Colour)c); Some of the monadic types have this wrapped up as a |
Beta Was this translation helpful? Give feedback.
Inheritance is obviously something that isn't used much in FP. However, we use it to represent discriminated unions - because there's no first class concept in C#.
One thing I tend to do is write constructor functions that always return the base class, which makes casting less problematic. I'll then use pattern-matching to get at the derived-types. For example, if we create a simple
Colour
union:I would add constructors to
Colour
: