0

So I wan't to have a generic function which works on any enum which is a flag and do a bitwise operation on it.

something like:

[Flags]
public enum MyEnum: long
{
 A = 0,
 B = 1 << 0,
}

public void Something<T>(ref T first, T other) where T : Enum/Flags/watever
{
 first = other << 1;
}

So how do I make this work? I can't use long nor Enum instead of T and I really don't want to duplicate this function because it's silly

ditoslav
  • 4,563
  • 10
  • 47
  • 79
  • You can't :-) You can't even "really" (with some caveats, see link) create a constraint on `Enum`. Link to similar question: http://stackoverflow.com/q/79126/613130 – xanatos Mar 08 '17 at 08:44
  • See also https://stackoverflow.com/questions/7244/anyone-know-a-good-workaround-for-the-lack-of-an-enum-generic-constraint – Cheng Chen Mar 08 '17 at 08:45
  • This is really sad – ditoslav Mar 08 '17 at 08:46
  • And then, there is really no compiler-enforced rule that a bitwise flag would have a value for `other << 1`. You could have a flag with value `0x1000` but don't have a flag for `0x2000`. – xanatos Mar 08 '17 at 08:46
  • Yeah but whenever you multiply int by 10000000 it can overflow. This looks like a part of a bigger problem where C# doesn't have sum types so we have to use this C hack called enums. Also: http://stackoverflow.com/questions/6413804/why-does-casting-int-to-invalid-enum-value-not-throw-exception – ditoslav Mar 08 '17 at 08:49

0 Answers0