I like switch expressions for mapping enums to values - while not the most scalable solution, it's fast and fairly clean if the enum represents something modal (and isn't huge).
One often source of bugs is adding members to an enum - which often leaves new cases unhandled.
But I think these bugs could be nearly wiped out if we could have compile errors for a non-exhaustive switch, making the omissions easily visible and fixable. (The default case has to be omitted though, otherwise it's all moot)
Is this possible? I'm thinking of something like this:
public string GetTargetValue()
{
return target switch
{
Target.A => "foo",
Target.B => "bar",
// Compile error if someone added Target.C, otherwise works fine
// no default case - it would defeat the point
};
}
P.S: I work primarily in Unity, but to my understanding newer versions of Unity use the Roslyn compiler (I don't use burst) so I assume that doesn't matter.
_ => throw new ArgumentOutOfRangeException(nameof(direction), $"Unexpected target value '{target}'."),
– Zischke(Target)5
would work even is there no equivalent for 5 in the enum. So forcing all valid values in a switch seems extremely tedious. – Physicalismtarget = (Target)5;
before the shown method what should happen? – Physicalism