DEV Community

Cover image for OneOf<Us> Discriminated Unions in C#

OneOf<Us> Discriminated Unions in C#

Matt Eland on September 22, 2019

Ever wish you could act on different types of variables - effectively switching by object type and taking different action depending on which class...
Collapse
 
mdfrenchman profile image
Mike French

I’ve used dynamic as the return type or a base type. With sub classes, ex: GuestUser, Admin etc inherit from User.
Then checking for result as Admin or something other way to conditionally action by type.

Worked very well in my implementation but I also controlled knowing WHAT the method could potentially return.

Collapse
 
integerman profile image
Matt Eland

That's an interesting idea. You're sort of undercutting the framework and it could be a minor performance impact, but the code is likely better. Any samples you can share?

Collapse
 
peledzohar profile image
Zohar Peled

Can types specified in the OneOf be non related? Because if the all implement the same interface this can be done using standard generics...

Collapse
 
sgatner profile image
Szymon Gatner

What about that Behavior Trees articles? ;)

Collapse
 
integerman profile image
Matt Eland

Thanks for the reminder. I believe I started that at one point, but a turn based behavior tree was underwhelming.