Skip to content

If you want to use `void` as a type parameter, but C# won't let you...

License

Notifications You must be signed in to change notification settings

badeend/Nothing

Repository files navigation

Nothing

If you want to use `void` as a type parameter, but C# won't let you...

Nuget


Badeend.Nothing is struct that contains... well... nothing!

Also known as a "unit" type in Functional Programming parlance.

In C# this can be used in places where you have nothing to return, but void is not allowed. Most notably: generics.

Example time!

Let's assume there exists an interface that you want to implement:

public interface IHandler<T>
{
  T Handle(MyInput input);
}

If your handler has nothing useful to return, then you would want to write this:

public class MyHandler : IHandler<void> // COMPILE ERROR!
{
  void Handle(MyInput input)
  {
    // (my implementation here)
  }
}

Unfortunately, "Computer Says No". C# won't let you.

If you're lucky enough to own that interface, you could decide to duplicate the interface and all related code: one for IHandler, and one for IHandler<T>.

If you're not able to change the interface or just don't feel like doing a bunch of unnecessary work; you could also change the type argument to Nothing:

using Badeend;

public class MyHandler : IHandler<Nothing> // <--- Nothing to see here
{
  Nothing Handle(MyInput input)
  {
    // (my implementation here)

    return Nothing.Value;
  }
}

Installation

NuGet Badeend.Nothing

dotnet add package Badeend.Nothing

Fake nothing keyword

Depending on how intensively you use this package, you might be interested in using Badeend.Globals.NothingKeyword, which exposes nothing as a top level field.

using Badeend;

public class MyHandler : IHandler<Nothing>
{
  Nothing Handle(MyInput input)
  {
    // (my implementation here)

    return nothing; // <--- Note the lowercase 'n'
  }
}

In C#10+ this can be configured as follows:

global using static Badeend.Globals.NothingKeyword;

or:

<ItemGroup>
  <Using Include="Badeend.Globals.NothingKeyword" Static="True" />
</ItemGroup>

Shameless self-promotion

May I interest you in one of my other packages?

  • Badeend.ValueCollections: Low overhead immutable collection types with structural equality.
  • Badeend.EnumClass: Discriminated unions for C# with exhaustiveness checking.
  • Badeend.Result: For failures that are not exceptional: Result<T,E> for C#.
  • Badeend.Any: Holds any value of any type, without boxing small structs (up to 8 bytes).
  • Badeend.Nothing: If you want to use void as a type parameter, but C# won't let you.

About

If you want to use `void` as a type parameter, but C# won't let you...

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Languages