I am just starting with Generics
in C# but have run into a problem early on, how can I call .HasFlag()
on a generic Enum
?
public class Example<TEnum> where TEnum : struct {
}
How can I add the [Flags]
attribute to it?
Calling the instance method will require boxing anyway, so, since you can't constrain to Enum
, just abandon generics and use Enum
. For example, instead of:
void Something(TEnum enumValue, TEnum flags)
{
if (enumValue.HasFlags(flags))
//do something ...
}
Do this:
void Something(Enum enumValue, Enum flags)
{
if (enumValue.HasFlags(flags))
//do something ...
}
In a generic method, you could achieve your goal like this:
void Something(TEnum enumValue, TEnum flags)
{
Enum castValue = (Enum)(object)enumValue;
Enum castFlags = (Enum)(object)flags;
if (castValue.HasFlags(castFlags))
//do something ...
}
This will throw an exception at runtime if you call the method with a value type that isn't an enum. You could also cast via ValueType
rather than object
, since the type parameter is known to represent a value type:
Enum castValue = (Enum)(ValueType)enumValue;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With