Remove need to set a default value in a switch expression when all possible solutions are provided #4875
-
I like the (new) switch expressions, but I don't understand why it wants me to implement a default when all possible solutions are provided when working with an enum. public enum MyEnum
{
A,
B,
C
} MyEnum myEnum= MyEnum.A;
string enumName = myEnum switch
{
MyEnum.A => "a",
MyEnum.B => "b",
MyEnum.C => "c",
_ => "why is this warning here for a default that is met"
} I don't understand why this is the way it is, that is why I put this in general and not in feature request. Also why can we not use |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Even though you only have the values using System;
MyEnum myenum = (MyEnum)(-1);
Console.WriteLine(myenum);
Console.WriteLine(myenum is MyEnum.A || myenum is MyEnum.B || myenum is MyEnum.C);
Console.WriteLine(Enum.IsDefined<MyEnum>(myenum));
Console.WriteLine(myenum switch
{
MyEnum.A => "a",
MyEnum.B => "b",
MyEnum.C => "c",
_ => "undefined"
});
public enum MyEnum
{
A,
B,
C
}
|
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
Even though you only have the values
A
,B
, andC
defined, the value of anyMyEnum
instance could be an undefined value. This is why theEnum.IsDefined
method exists.Enum.IsDefined
: https://docs.microsoft.com/en-us/dotnet/api/system.enum.isdefined