Something like the following should work. There still is casting
involved when calling the method, but you can take advantage of
generics for the return value. So you wouldn't need the method for
every enum, just every integral type.
static T SwapEnumFlag<T>(int flags, int flag) where T : struct
{
Debug.Assert(typeof(T).IsEnum, "T must be an enum");
Debug.Assert(typeof(T).IsDefined(typeof(FlagsAttri bute), false), "T
must have the System.FlagsAttribute applied to it.");
if ((flags & flag) == flag)
flags &= ~flag;
else
flags |= flag;
return (T)Enum.ToObject(typeof(T), flags);
}
FlaggedEnum flagged = FlaggedEnum.Red | FlaggedEnum.Blue;
Debug.WriteLine(flagged); // output: Red, Blue
flagged = SwapEnumFlag<FlaggedEnum>((int)flagged,
(int)FlaggedEnum.Red);
Debug.WriteLine(flagged); // output: Blue
flagged = SwapEnumFlag<FlaggedEnum>((int)flagged,
(int)FlaggedEnum.Red);
Debug.WriteLine(flagged); // output: Red, Blue
Jack Robertson wrote:
Hi there,
Is it possible to write the following function as a template where
"EnumFlags" becomes template parameter T (where T will always be an
enumerator with the "FlagsAttribute"). Nothing I've tried works, including
use of a "where" clause since T must always be of type "System.Enum". Thanks
in advance.
void SetFlag(EnumFlags Flag, ref EnumFlags Flags, bool On)
{
if (On)
{
Flags |= Flag;
}
else
{
Flags &= ~Flag;
}
}