Code Inspection: Some values of the enum are not processed inside switch expression and are handled via exception in default arm
When using a switch expression with an enum
, it is not required to have arms for each enum value — these values will be processed in the _
discard.
This might be intended by the author to handle some unimportant values. But if the _
discard throws an exception, all usages of the switch
with non-processed enum
values will also throw the exception, which is probably a consequence of adding a new value to the enum
and forgetting to update the switch
accordingly.
enum MyColor { Red, Green, Blue }
string GetColor(MyColor color) => color switch
{
MyColor.Red => "Red",
MyColor.Green => "Green",
_ => throw new ArgumentOutOfRangeException(nameof(color))
};
// The value 'Blue' is not processed in the switch
// so this call will throw an exception
string TestColors => GetColor(MyColor.Blue);
Last modified: 21 March 2024