Skip to content

Instantly share code, notes, and snippets.

@djeikyb
Last active October 29, 2021 00:25
Show Gist options
  • Save djeikyb/48ec0b7362b1676c01c2ab50b6d9d560 to your computer and use it in GitHub Desktop.
Save djeikyb/48ec0b7362b1676c01c2ab50b6d9d560 to your computer and use it in GitHub Desktop.
An exception to throw in the default branch of a switch..case that ought to be exhaustive
using System;
namespace Example
{
/// <summary>
/// </summary>
/// <typeparam name="T">Must be an enum type</typeparam>
/// <remarks>
/// Follows the pattern of <see cref="SwitchExpressionException"/>
/// </remarks>
public class EnumSwitchException<T> : InvalidOperationException
where T : Enum
{
public EnumSwitchException(T actualValue)
: base(
$"Some values of the enum {typeof(T)} are not processed inside switch: {actualValue}"
)
{
}
}
}
@djeikyb
Copy link
Author

djeikyb commented Oct 29, 2021

Use like:

public string Convert(SomeEnum arg)
{
  return arg switch
  {
    SomeEnum.A => "branch a",
    SomeEnum.B => "branch b",
    _ => throw new EnumSwitchException<SomeEnum>(arg),
  };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment