Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Equivalent for C++ std::variant (sum type)

In C++ we have std::variant for creating a sum-types.
For example, the following will allow v to hold either a std::string or an int:

#include <variant>
#include <string>

//...

std::variant< std::string, int> v;
v = "aaa";  // now v holds a std::string
v = 5;      // now v holds an int

In addition – the compiler will enforce that you assign v only with values convertible to std::string or int.

I am looking for a similar construct in C#.
Had a look at this post: Variant Type in C#,
but it didn’t offer the proper equivalent I am looking for.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there one in C#?


Edit:
The SO post Discriminated union in C# is related but does not exactly answer my question because I am looking for a general language construct and not for a solution for a specific case.
However one of the answers mentioned the OneOf library, which is also one of the solutions in the accepted answer here.

>Solution :

You can use Either monad from library language-ext. Install LanguageExt.Core NuGet package.

using LanguageExt;

//...

Either<string, int> v;
v = "aaa";
v = 5;

Or you could use OneOf library. Install OneOf NuGet package.

using OneOf;

//...

OneOf<string, int> v;
v = "aaa";
v = 5;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading