This was recently asked in the Code Project Q/A forums, and while there were several responses posted, I think the following is succint and works well.
private static bool IsValidFlagValue<T>(int x) where T : struct
{
int aggregate = Enum.GetValues(
typeof(T)).Cast<int>().Aggregate((z, y) => z | y);
return x <= aggregate && (aggregate & x) > 0;
}
Note that it does not handle a case where the flag-enum has a 0-value. Here’s a version that does that too (a little less brief).
private static bool IsValidFlagValue<T>(int x) where T : struct
{
var values = Enum.GetValues(typeof(T)).Cast<int>();
if (x == 0 && values.Contains(0))
{
return true;
}
int aggregate = values.Aggregate((z, y) => z | y);
return x <= aggregate && (aggregate & x) > 0;
}