I have an enum
:
public enum Flags {
COMMAND_MSG = 1,
COMMAND_FILE = 2,
COMMAND_ACTION = 4,
}
Now , suppose I set multiple values like :
Flags g = Flags.COMMAND_ACTION |Flags.COMMAND_MSG;
So I have an int with value 5
.
Now , from that 5
I want to see that it's a combination of : Flags.COMMAND_ACTION |Flags.COMMAND_MSG;
(Notice , I dont have [Flags]
attribute because I'm using protobuff library , and the enum is auto generated.
What have I tried :
public string Show (Flags item)
{
var s="";
string.Join(",", Enum.GetValues(typeof(Flags))
.Cast<Flags>()
.Select(f=>(f & item) >0 ?f.ToString() :"") //check if bit is set
.Where(f=>!string.IsNullOrWhiteSpace(f))); //remove empty
return s;
}
So Show(5);
does display : COMMAND_MSG,COMMAND_ACTION
So where is the problem ?
I wanted to convert it to a generic extension method :
public static string ToFlags<T>(this int val, T FlagType) where T : ??
{
return string.Join(",", Enum.GetValues(typeof(T))
.Cast<T>()
.Select(enumEntry => (enumEntry & val) > 0 ? enumEntry.ToString() : "")
.Where(f => !string.IsNullOrWhiteSpace(f)));
}
But there's an error because :
Question :
Which generic constraint should I apply in order for this to work ?