This roslyn analyzer solves the problem of non-exhaustive switches on enums. It generates a warning when a switch is non-exhaustive.
public enum Status
{
Accepted = 1,
Cooking = 2,
Cooked = 3,
}
public static void Method(Status status)
{
switch (status)
{
case Status.Accepted:
return;
default:
throw new ArgumentOutOfRangeException(nameof(status), status, null);
}
}
public static void Method(Status status)
{
switch (status)
{
case Status.Accepted:
return;
case Status.Cooking:
throw new NotImplementedException();
case Status.Cooked:
throw new NotImplementedException();
default:
throw new ArgumentOutOfRangeException(nameof(status), status, null);
}
}
public static string Method(Status status)
{
return status switch
{
Status.Accepted => "",
_ => throw new ArgumentOutOfRangeException(nameof(status), status, null)
};
}
public static string Method(Status status)
{
return status switch
{
Status.Accepted => "",
Status.Cooking => throw new NotImplementedException(),
Status.Cooked => throw new NotImplementedException(),
_ => throw new ArgumentOutOfRangeException(nameof(status), status, null)
};
}
Also, you can make a compiler treat the warning as an error, like this:
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<WarningsAsErrors>ExhaustiveSwitchOnEnums</WarningsAsErrors>
</PropertyGroup>
Feel free to write me about any problems.