CSharpEssentials.Any 8.0.0

dotnet add package CSharpEssentials.Any --version 8.0.0
                    
NuGet\Install-Package CSharpEssentials.Any -Version 8.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CSharpEssentials.Any" Version="8.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CSharpEssentials.Any" Version="8.0.0" />
                    
Directory.Packages.props
<PackageReference Include="CSharpEssentials.Any" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add CSharpEssentials.Any --version 8.0.0
                    
#r "nuget: CSharpEssentials.Any, 8.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package CSharpEssentials.Any@8.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=CSharpEssentials.Any&version=8.0.0
                    
Install as a Cake Addin
#tool nuget:?package=CSharpEssentials.Any&version=8.0.0
                    
Install as a Cake Tool

CSharpEssentials.Any

Discriminated unions (sum types) for .NET: Any<T0, T1> through Any<T0, ..., T7> hold a value of one of 2 to 8 fixed types. They support implicit conversions, Switch and Match, type helpers (Is, As, TryAs, Deconstruct, ToTuple), Partition and Traverse over sequences, and JSON.

Benchmarks against OneOf 3.0.271 and Dunet 1.16.2 (construct, match, try-pick, partition, JSON and ToString) are in BENCHMARKS.md.

Installation

dotnet add package CSharpEssentials.Any

Targets net11.0, net10.0, net9.0 and netstandard2.1. Depends on CSharpEssentials.Json and CSharpEssentials.Core. The types live in the CSharpEssentials.Any namespace.

Usage

Creating unions

using CSharpEssentials.Any;

Any<string, int> ParseInput(string input)
{
    if (int.TryParse(input, out int n))
        return n; // implicit to Any<string, int>
    return input;
}

Any<string, int> first = Any<string, int>.First("text");   // explicit factories: First, Second, Third ... Eighth
Any<string, int> second = Any.Create<string, int>(5);      // or Any.Create with the type arguments spelled out

The union holds its active branch in Index (0 for the first type) and its value in Value (object?, so a value-type branch is boxed). Implicit conversion is ambiguous when two type arguments are the same type, for example Any<int, int>. default(Any<...>) has Index 0 but a null Value, so IsFirst is true while GetFirst() returns null or default.

Pattern matching

Any<string, int> result = ParseInput("123");

// Match returns AnyActionResult<TResult>: Status tells whether a handler ran, Result holds its value
AnyActionResult<string> output = result.Match(
    first: str => $"String: {str}",
    second: num => $"Number: {num}");
Console.WriteLine(output.Result);

AnyActionStatus status = result.Switch(
    first: str => Console.WriteLine("It's a string"),
    second: num => Console.WriteLine("It's a number"));

Every handler is optional, so the compiler does not check that all branches are handled. When the active branch has no handler, Switch returns AnyActionStatus.NotExecuted and Match returns an AnyActionResult whose Status is NotExecuted and whose Result is default; otherwise the status is Executed. Calling Match or Switch on default(Any<...>), or on a union that holds null, throws InvalidOperationException.

Type checking

if (result.IsSecond)
{
    int val = result.GetSecond();   // throws InvalidOperationException when another branch is active
}

// Generic helpers: the target type first, then the union's type arguments
bool isInt = result.Is<int, string, int>();
int? asInt = result.As<int, string, int>();
bool found = result.TryAs<int, string, int>(out int value);

// Deconstruct and ToTuple: the inactive branches are default
var (text, number) = result;
(string? First, int Second) tuple = result.ToTuple();

IsFirst through IsEighth and GetFirst() through GetEighth() exist up to the arity of the union. Is, As and TryAs test the runtime type of the value, not the branch. For a value-type target, As returns default (so 0 for int) when the value is of another type, not null; use Is or TryAs to tell the cases apart.

JSON and ToString

A union serializes to JSON as {"Index":1,"Value":123} and deserializes back to the same branch. The value is read with the JsonSerializerOptions you pass to JsonSerializer, so a naming policy or converter applies to it too. A null value deserializes when the branch type is a reference type or Nullable<T>, and throws ArgumentNullException for any other value-type branch. ToString() returns the value's own ToString(), or an empty string when the value is null; it does not use reflection, so it is safe under trimming and Native AOT.

Collection extensions

Partition and Traverse scatter a sequence of unions into one typed array per branch in one pass, for every arity:

// Classify API responses into successes and errors
var (users, errors) = responses
    .Traverse(r => ClassifyResponse(r));  // returns Any<UserDto, ApiError>

// Or partition an existing sequence of unions
var (drafts, published) = articles
    .Select(a => GetState(a))             // returns Any<Draft, Published>
    .Partition();

Upgrading to 8.0

  • A null value is now accepted when its branch is a reference type or Nullable<T>. This applies to JSON deserialization ({"Index":n,"Value":null} now round-trips) and to the public (int index, object? value) constructor, so new Any<int, string>(1, null) no longer throws. Earlier versions threw ArgumentNullException for every null value. If you relied on that to reject such input, check Value is null after constructing or deserializing.
  • JSON deserialization now reads the value with the caller's JsonSerializerOptions. Earlier versions ignored them and always used EnhancedJsonSerializerOptions.DefaultOptions (camelCase, case-insensitive, enum and date converters), so a snake_case payload lost its properties. If your payloads relied on those defaults, pass EnhancedJsonSerializerOptions.DefaultOptions (or options with the same settings) to JsonSerializer.Deserialize. With a source-generated JsonSerializerContext, register each branch type with [JsonSerializable]; an unregistered branch type now throws NotSupportedException on deserialization.
  • ToString() now returns the value's own ToString() instead of its JSON, so a string value comes back without quotes (text, not "text"), an object returns its type's ToString() instead of a JSON object, and a null value returns an empty string instead of null. The old output came from reflection-based System.Text.Json, which is not safe under Native AOT. If you need the JSON, call JsonSerializer.Serialize(any.Value, options) with your own options or source-generated context.
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed.  net11.0 is compatible. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on CSharpEssentials.Any:

Package Downloads
CSharpEssentials

A comprehensive C# library enhancing functional programming capabilities with type-safe monads (Maybe, Result), discriminated unions (Any), and robust error handling. Features include: domain-driven design support, enhanced Entity Framework integration, testable time management, JSON utilities, and LINQ extensions. Built for modern C# development with focus on maintainability, testability, and functional programming principles.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
8.0.0 161 11/9/2026
7.0.0 163 10/20/2026
6.5.2 144 10/10/2026
6.5.1 133 10/10/2026
6.5.0 140 10/9/2026
6.4.0 136 10/9/2026
6.3.0 146 10/8/2026
6.2.0 137 10/8/2026
6.1.0 141 10/7/2026
6.0.0 136 10/7/2026
5.2.1 143 10/7/2026
5.2.0 145 10/7/2026
5.1.0 134 10/7/2026
5.0.0 131 10/6/2026
4.1.0 138 10/6/2026
4.0.0 132 10/5/2026
3.2.3 335 5/31/2026
3.2.2 175 5/31/2026
3.2.1 169 5/31/2026
3.2.0 167 5/30/2026
Loading failed