DEV Community

Cover image for OneOf Library in C#
Takat Wicaksono
Takat Wicaksono

Posted on

OneOf Library in C#

Introduction

The OneOf library in C# is a utility designed to handle scenarios where a value can be one of several different types. It allows you to create a type-safe union of multiple types, meaning that a variable can hold one of several possible types, but not more than one at a time.

Story Of OneOf Library

The story of the OneOf library is rooted in a common challenge that many developers face: handling scenarios where a method or function needs to return one of several possible types. This problem is particularly prevalent in complex applications where different outcomes might need to be represented by different data types. Traditionally, developers might use object types, complex inheritance hierarchies, or rely on out parameters and tuples to achieve this, but these approaches often sacrifice type safety, clarity, and ease of use.

The Problem: Handling Multiple Return Types
Vladimir Khorikov, the creator of the OneOf library, is an advocate for clean, maintainable code and domain-driven design (DDD). He recognized that developers frequently needed a way to handle multiple possible return types in a more type-safe and expressive manner. For instance, when a method might return either a success result, an error message, or perhaps even some other state, developers often found themselves in situations where:

  1. They had to return a base type (like object), losing the benefits of type safety.
  2. They implemented complex inheritance models, which could lead to rigid and hard-to-maintain code.
  3. They used tuples or out parameters, which could make code harder to read and maintain.

The Solution: Introducing OneOf
To address these issues, Vladimir Khorikov developed the OneOf library, which was designed to introduce the concept of union types to C#. In functional programming languages, union types (or "sum types") allow a value to be one of several different, predefined types. This concept was less prevalent in C#, a language primarily oriented around object-oriented programming, so OneOf filled a significant gap.

The library provided a simple and elegant way to define a method that could return multiple different types, without losing type safety. This was achieved by creating a OneOf type, which could hold exactly one value of any of the specified types.

Adoption and Impact
Since its creation, the OneOf library has become a popular tool among C# developers who are looking for a more flexible and type-safe way to handle multiple return types. It gained traction because it allowed developers to write cleaner, more maintainable code without the downsides of previous approaches. The library was also particularly appealing in scenarios involving domain-driven design (DDD), where clearly expressing different domain concepts is crucial.

The OneOf library is often used in:

  • Error Handling: Returning different types of errors or success results.
  • API Responses: Handling multiple types of responses in a single API endpoint.
  • Domain Modeling: Representing domain concepts that can have different states or outcomes.

Community and Open Source
As an open-source project, OneOf quickly attracted attention from the C# community. Developers appreciated its simplicity and the way it integrated with the language's existing features. The project is hosted on GitHub, where it continues to be maintained and improved by Vladimir and the broader community. Contributions, bug reports, and feature requests from users have helped to refine and enhance the library over time.

The Legacy
OneOf exemplifies how a simple, focused tool can have a significant impact on the way developers write code. It addresses a specific problem in a way that is both elegant and effective, making it a go-to solution for developers needing to represent multiple possible outcomes in a type-safe manner.

The library is a testament to the power of open-source development and the importance of community-driven tools in modern software development. Through OneOf, Vladimir Khorikov has provided developers with a valuable tool that aligns with the principles of clean code and robust software design.

Key Features of the OneOf Library:

  • Type Safety: Ensures that only the defined types can be used, reducing the risk of runtime errors.
  • Pattern Matching: Allows you to use pattern matching to handle each possible type that a OneOf variable might hold.
  • Simplified Error Handling: Commonly used to represent results that can either be successful (with a value) or an error (with a different type).

Installation:

To add the OneOf library to your C# project, you can install it via NuGet, the package manager for .NET. Here's how you can do it:

Using the .NET CLI

  1. Open a terminal or command prompt.
  2. Navigate to your project directory.
  3. Run the following command:


dotnet add package OneOf


Enter fullscreen mode Exit fullscreen mode

This command adds the OneOf library to your project and updates the project file accordingly.

Using Visual Studio

  1. Open your project in Visual Studio.
  2. Right-click on your project in the Solution Explorer and select Manage NuGet Packages.
  3. In the NuGet Package Manager, search for “OneOf”.
  4. Select the package named OneOf by Vladimir Khorikov.
  5. Click Install to add it to your project.

Using Package Manager Console in Visual Studio

  1. Open Visual Studio.
  2. Go to Tools > NuGet Package Manager > Package Manager Console.
  3. In the console, run the following command:


Install-Package OneOf


Enter fullscreen mode Exit fullscreen mode

Adding Directly to the .csproj File
Alternatively, you can add the OneOf library directly to your project's .csproj file by including the following line within the section for package references:



<PackageReference Include="OneOf" Version="1.1.1" />


Enter fullscreen mode Exit fullscreen mode

Make sure to use the latest version of the library available on NuGet.

Using Library:
Once the package is installed, you can start using the OneOf library in your code by adding the necessary using directive:



using OneOf;


Enter fullscreen mode Exit fullscreen mode

This allows you to utilize the OneOf type in your project.

Example Usage:
Here’s a simple example to demonstrate how you might use OneOf:



static OneOf<string, int> TakeThat(bool bString){
    if (bString) {
        return GenerateRandomWord(6);
    }
    return new Random().Next();
}
static string GenerateRandomWord(int length) {
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    StringBuilder result = new StringBuilder(length);
    Random random = new Random();

    for (int i = 0; i < length; i++) {
        result.Append(chars[random.Next(chars.Length)]);
    }

    return result.ToString();
}
static void Main(string[] args) {
    var result = TakeThat(true);
    result.Switch(
        str => Console.WriteLine($"String: {str}"),
        number => Console.WriteLine($"Number: {number}")
    );
}


Enter fullscreen mode Exit fullscreen mode

Image description
Key Concepts:

  • Union Type: OneOf represents a value that could be one of several types (e.g., OneOf).
  • Switch Method: Allows handling each possible type with a corresponding action.
  • Match Method: Returns a value based on the type of the held value.

The OneOf library is especially useful in scenarios where you want to return different types from a method or function without resorting to using base types like object or complex inheritance structures. It is a popular choice in situations where a method might return either a successful result or an error message, among other use cases.

Top comments (0)