If you want to use `void` as a type parameter, but C# won't let you...
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.
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;
}
}
dotnet add package Badeend.Nothing
Depending on how intensively you use this package, you might be interested in using Badeend.Nothing.Keyword
globally, 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.Nothing.Keyword;
or:
<ItemGroup>
<Using Include="Badeend.Nothing.Keyword" Static="True" />
</ItemGroup>
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.