Skip to content

Casting a Validation #1125

Answered by louthy
speterson-zoll asked this question in Q&A
Oct 5, 2022 · 1 comments · 1 reply
Discussion options

You must be logged in to vote

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:

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 Colour:

public abstract record Colour
{
    public static Colour Red(int amount) => new Red(am…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@speterson-zoll
Comment options

Answer selected by speterson-zoll
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants