Home > Blockchain >  C# Equivalent for C std::variant (sum type / discriminated-union)
C# Equivalent for C std::variant (sum type / discriminated-union)

Time:11-22

In C we have std::variant for creating a sum-types (AKA discriminated-union).
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.

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.

CodePudding user response:

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;

UPDATE

Just to point it out: LanguageExt supports only 2 types in the Either struct. But OneOf supports up to 8 types. Although I am not aware which one is more performant and feature rich.

CodePudding user response:

you can use object

  object v;
  v = "aaa";
  v = 42;
  • Related