Feature request: C# 7.3 enum generic constraint not being able to compare to default() #2694
-
I am unable to compare a restricted type parameter to it's default(). Rough Example: public class MyClass<TEnum> where TEnum : System.Enum
{
public bool SomeMethod(TEnum myEnum)
{
return default(TEnum) == myEnum;
}
} This throws the compiler error:
Do I need to do something else? |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
That code will not work since the size of the enum isn't known at compile time (and the type literally could be |
Beta Was this translation helpful? Give feedback.
-
Thanks for the explanation. Are there additional generic constraints that could clear that up at compile time? Either existing or proposed/planned? |
Beta Was this translation helpful? Give feedback.
-
Does I think you want this: using System.Collections.Generic;
public class MyClass<TEnum> where TEnum : struct, System.Enum
{
public bool SomeMethod(TEnum myEnum)
{
return EqualityComparer<TEnum>.Default.Equals(default, myEnum);
}
} |
Beta Was this translation helpful? Give feedback.
-
It sure seems like it. sharplab |
Beta Was this translation helpful? Give feedback.
-
It's possible that the 'Shapes' proposal would cover this. |
Beta Was this translation helpful? Give feedback.
That code will not work since the size of the enum isn't known at compile time (and the type literally could be
System.Enum
not a subclass), so there's no way to know which==
to call. You can replace the above withdefault(TEnum).Equals(myEnum)
though.