<p>What I want to do is something like this: I have enums with combined flagged values.</p>

<pre><code>public static class EnumExtension
{
    public static bool IsSet&lt;T&gt;( this T input, T matchTo ) 
        where T:enum //the constraint I want that doesn't exist in C#3
    {    
        return (input &amp; matchTo) != 0;
    }
}
</code></pre>

<p>So then I could do:</p>

<pre><code>MyEnum tester = MyEnum.FlagA | MyEnum.FlagB

if( tester.IsSet( MyEnum.FlagA ) )
    //act on flag a
</code></pre>

<p>Unfortunately, C#'s generic where constraints have no enum restriction, only class and struct. C# doesn't see enums as structs (even though they are value types) so I can't add extension types like this.</p>

<p>Does anyone know a workaround?</p>

[{'answer_id': 7385, 'author': 'Ronnie', 'author_id': 193, 'author_profile': 'https://Stackoverflow.com/users/193', 'pm_score': 4, 'selected': False, 'text': '<p>Darren, that would work if the types were specific enumerations - for general enumerations to work you have to cast them to ints (or more likely uint) to do the boolean math:</p>\n\n<pre><code>public static bool IsSet( this Enum input, Enum matchTo )\n{\n    return ( Convert.ToUInt32( input ) &amp; Convert.ToUInt32( matchTo ) ) != 0;\n}\n</code></pre>\n'}, {'answer_id': 13517, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 1, 'selected': False, 'text': '<p>Using your original code, inside the method you can also use reflection to test that T is an enum:</p>\n\n<pre><code>public static class EnumExtension\n{\n    public static bool IsSet&lt;T&gt;( this T input, T matchTo )\n    {\n        if (!typeof(T).IsEnum)\n        {\n            throw new ArgumentException("Must be an enum", "input");\n        }\n        return (input &amp; matchTo) != 0;\n    }\n}\n</code></pre>\n'}, {'answer_id': 1188323, 'author': 'thecoop', 'author_id': 79439, 'author_profile': 'https://Stackoverflow.com/users/79439', 'pm_score': 2, 'selected': False, 'text': "<p>The way I do it is put a struct constraint, then check that T is an enum at runtime. This doesn't eliminate the problem completely, but it does reduce it somewhat</p>\n"}, {'answer_id': 1409873, 'author': 'Jon Skeet', 'author_id': 22656, 'author_profile': 'https://Stackoverflow.com/users/22656', 'pm_score': 7, 'selected': True, 'text': '<p><strong>EDIT: This is now live in version 0.0.0.2 of UnconstrainedMelody.</strong></p>\n\n<p>(As requested on my <a href="http://codeblog.jonskeet.uk/2009/09/10/generic-constraints-for-enums-and-delegates/" rel="noreferrer">blog post about enum constraints</a>. I\'ve included the basic facts below for the sake of a standalone answer.)</p>\n\n<p>The best solution is to wait for me to include it in <a href="https://github.com/jskeet/unconstrained-melody" rel="noreferrer">UnconstrainedMelody</a><sup>1</sup>. This is a library which takes C# code with "fake" constraints such as</p>\n\n<pre><code>where T : struct, IEnumConstraint\n</code></pre>\n\n<p>and turns it into</p>\n\n<pre><code>where T : struct, System.Enum\n</code></pre>\n\n<p>via a postbuild step.</p>\n\n<p>It shouldn\'t be too hard to write <code>IsSet</code>... although catering for both <code>Int64</code>-based and <code>UInt64</code>-based flags could be the tricky part. (I smell some helper methods coming on, basically allowing me to treat any flags enum as if it had a base type of <code>UInt64</code>.)</p>\n\n<p>What would you want the behaviour to be if you called</p>\n\n<pre><code>tester.IsSet(MyFlags.A | MyFlags.C)\n</code></pre>\n\n<p>? Should it check that <em>all</em> the specified flags are set? That would be my expectation.</p>\n\n<p>I\'ll try to do this on the way home tonight... I\'m hoping to have a quick blitz on useful enum methods to get the library up to a usable standard quickly, then relax a bit.</p>\n\n<p>EDIT: I\'m not sure about <code>IsSet</code> as a name, by the way. Options:</p>\n\n<ul>\n<li>Includes</li>\n<li>Contains</li>\n<li>HasFlag (or HasFlags)</li>\n<li>IsSet (it\'s certainly an option)</li>\n</ul>\n\n<p>Thoughts welcome. I\'m sure it\'ll be a while before anything\'s set in stone anyway...</p>\n\n<hr>\n\n<p><sup>1</sup> or submit it as a patch, of course...</p>\n'}, {'answer_id': 1416703, 'author': 'SLaks', 'author_id': 34397, 'author_profile': 'https://Stackoverflow.com/users/34397', 'pm_score': 3, 'selected': False, 'text': '<p>Actually, it is possible, with an ugly trick.\nHowever, it cannot be used for extension methods.</p>\n\n<pre><code>public abstract class Enums&lt;Temp&gt; where Temp : class {\n    public static TEnum Parse&lt;TEnum&gt;(string name) where TEnum : struct, Temp {\n        return (TEnum)Enum.Parse(typeof(TEnum), name); \n    }\n}\npublic abstract class Enums : Enums&lt;Enum&gt; { }\n\nEnums.IsSet&lt;DateTimeKind&gt;("Local")\n</code></pre>\n\n<p>If you want to, you can give <code>Enums&lt;Temp&gt;</code> a private constructor and a public nested abstract inherited class with <code>Temp</code> as <code>Enum</code>, to prevent inherited versions for non-enums.</p>\n'}, {'answer_id': 1416806, 'author': 'Brian Surowiec', 'author_id': 39605, 'author_profile': 'https://Stackoverflow.com/users/39605', 'pm_score': 1, 'selected': False, 'text': '<p>Here\'s some code that I just did up that seems to work like you want without having to do anything too crazy. It\'s not restricted to only enums set as Flags, but there could always be a check put in if need be.</p>\n\n<pre><code>public static class EnumExtensions\n{\n    public static bool ContainsFlag(this Enum source, Enum flag)\n    {\n        var sourceValue = ToUInt64(source);\n        var flagValue = ToUInt64(flag);\n\n        return (sourceValue &amp; flagValue) == flagValue;\n    }\n\n    public static bool ContainsAnyFlag(this Enum source, params Enum[] flags)\n    {\n        var sourceValue = ToUInt64(source);\n\n        foreach (var flag in flags)\n        {\n            var flagValue = ToUInt64(flag);\n\n            if ((sourceValue &amp; flagValue) == flagValue)\n            {\n                return true;\n            }\n        }\n\n        return false;\n    }\n\n    // found in the Enum class as an internal method\n    private static ulong ToUInt64(object value)\n    {\n        switch (Convert.GetTypeCode(value))\n        {\n            case TypeCode.SByte:\n            case TypeCode.Int16:\n            case TypeCode.Int32:\n            case TypeCode.Int64:\n                return (ulong)Convert.ToInt64(value, CultureInfo.InvariantCulture);\n\n            case TypeCode.Byte:\n            case TypeCode.UInt16:\n            case TypeCode.UInt32:\n            case TypeCode.UInt64:\n                return Convert.ToUInt64(value, CultureInfo.InvariantCulture);\n        }\n\n        throw new InvalidOperationException("Unknown enum type.");\n    }\n}\n</code></pre>\n'}, {'answer_id': 1769785, 'author': 'Phil Devaney', 'author_id': 88468, 'author_profile': 'https://Stackoverflow.com/users/88468', 'pm_score': 2, 'selected': False, 'text': '<p>This doesn\'t answer the original question, but there is now a method in .NET 4 called <a href="http://msdn.microsoft.com/en-us/library/system.enum.hasflag%28VS.100%29.aspx" rel="nofollow noreferrer">Enum.HasFlag</a> which does what you are trying to do in your example</p>\n'}, {'answer_id': 11574563, 'author': 'Simon', 'author_id': 53158, 'author_profile': 'https://Stackoverflow.com/users/53158', 'pm_score': 3, 'selected': False, 'text': '<p>You can achieve this using IL Weaving and <a href="https://github.com/Fody/ExtraConstraints" rel="noreferrer">ExtraConstraints</a></p>\n\n<p><strong>Allows you to write this code</strong></p>\n\n<pre><code>public class Sample\n{\n    public void MethodWithDelegateConstraint&lt;[DelegateConstraint] T&gt; ()\n    {        \n    }\n    public void MethodWithEnumConstraint&lt;[EnumConstraint] T&gt;()\n    {\n    }\n}\n</code></pre>\n\n<p><strong>What gets compiled</strong></p>\n\n<pre><code>public class Sample\n{\n    public void MethodWithDelegateConstraint&lt;T&gt;() where T: Delegate\n    {\n    }\n\n    public void MethodWithEnumConstraint&lt;T&gt;() where T: struct, Enum\n    {\n    }\n}\n</code></pre>\n'}, {'answer_id': 36078862, 'author': 'Jürgen Steinblock', 'author_id': 98491, 'author_profile': 'https://Stackoverflow.com/users/98491', 'pm_score': 0, 'selected': False, 'text': '<p>I just wanted to add Enum as a generic constraint.</p>\n\n<p>While this is just for a tiny helper method using <a href="https://www.github.com/Fody/ExtraConstraints" rel="nofollow noreferrer"><code>ExtraConstraints</code></a> is a bit too much overhead for me.</p>\n\n<p>I decided to just just create a <code>struct</code> constraint and add a runtime check for <code>IsEnum</code>. For converting a variable from T to Enum I cast it to object first.</p>\n\n<pre><code>    public static Converter&lt;T, string&gt; CreateConverter&lt;T&gt;() where T : struct\n    {\n        if (!typeof(T).IsEnum) throw new ArgumentException("Given Type is not an Enum");\n        return new Converter&lt;T, string&gt;(x =&gt; ((Enum)(object)x).GetEnumDescription());\n    }\n</code></pre>\n'}, {'answer_id': 41278947, 'author': 'SoLaR', 'author_id': 1011436, 'author_profile': 'https://Stackoverflow.com/users/1011436', 'pm_score': 0, 'selected': False, 'text': '<p>if someone needs generic IsSet (created out of box on fly could be improved on), and or string to Enum onfly conversion (which uses EnumConstraint presented below):</p>\n\n<pre><code>  public class TestClass\n  { }\n\n  public struct TestStruct\n  { }\n\n  public enum TestEnum\n  {\n    e1,    \n    e2,\n    e3\n  }\n\n  public static class TestEnumConstraintExtenssion\n  {\n\n    public static bool IsSet&lt;TEnum&gt;(this TEnum _this, TEnum flag)\n      where TEnum : struct\n    {\n      return (((uint)Convert.ChangeType(_this, typeof(uint))) &amp; ((uint)Convert.ChangeType(flag, typeof(uint)))) == ((uint)Convert.ChangeType(flag, typeof(uint)));\n    }\n\n    //public static TestClass ToTestClass(this string _this)\n    //{\n    //  // #generates compile error  (so no missuse)\n    //  return EnumConstraint.TryParse&lt;TestClass&gt;(_this);\n    //}\n\n    //public static TestStruct ToTestStruct(this string _this)\n    //{\n    //  // #generates compile error  (so no missuse)\n    //  return EnumConstraint.TryParse&lt;TestStruct&gt;(_this);\n    //}\n\n    public static TestEnum ToTestEnum(this string _this)\n    {\n      // #enum type works just fine (coding constraint to Enum type)\n      return EnumConstraint.TryParse&lt;TestEnum&gt;(_this);\n    }\n\n    public static void TestAll()\n    {\n      TestEnum t1 = "e3".ToTestEnum();\n      TestEnum t2 = "e2".ToTestEnum();\n      TestEnum t3 = "non existing".ToTestEnum(); // default(TestEnum) for non existing \n\n      bool b1 = t3.IsSet(TestEnum.e1); // you can ommit type\n      bool b2 = t3.IsSet&lt;TestEnum&gt;(TestEnum.e2); // you can specify explicite type\n\n      TestStruct t;\n      // #generates compile error (so no missuse)\n      //bool b3 = t.IsSet&lt;TestEnum&gt;(TestEnum.e1);\n\n    }\n\n  }\n</code></pre>\n\n<p>If someone still needs example hot to create Enum coding constraint:</p>\n\n<pre><code>using System;\n\n/// &lt;summary&gt;\n/// would be same as EnumConstraint_T&amp;lt;Enum&gt;Parse&amp;lt;EnumType&gt;("Normal"),\n/// but writen like this it abuses constrain inheritence on System.Enum.\n/// &lt;/summary&gt;\npublic class EnumConstraint : EnumConstraint_T&lt;Enum&gt;\n{\n\n}\n\n/// &lt;summary&gt;\n/// provides ability to constrain TEnum to System.Enum abusing constrain inheritence\n/// &lt;/summary&gt;\n/// &lt;typeparam name="TClass"&gt;should be System.Enum&lt;/typeparam&gt;\npublic abstract class EnumConstraint_T&lt;TClass&gt;\n  where TClass : class\n{\n\n  public static TEnum Parse&lt;TEnum&gt;(string value)\n    where TEnum : TClass\n  {\n    return (TEnum)Enum.Parse(typeof(TEnum), value);\n  }\n\n  public static bool TryParse&lt;TEnum&gt;(string value, out TEnum evalue)\n    where TEnum : struct, TClass // struct is required to ignore non nullable type error\n  {\n    evalue = default(TEnum);\n    return Enum.TryParse&lt;TEnum&gt;(value, out evalue);\n  }\n\n  public static TEnum TryParse&lt;TEnum&gt;(string value, TEnum defaultValue = default(TEnum))\n    where TEnum : struct, TClass // struct is required to ignore non nullable type error\n  {    \n    Enum.TryParse&lt;TEnum&gt;(value, out defaultValue);\n    return defaultValue;\n  }\n\n  public static TEnum Parse&lt;TEnum&gt;(string value, TEnum defaultValue = default(TEnum))\n    where TEnum : struct, TClass // struct is required to ignore non nullable type error\n  {\n    TEnum result;\n    if (Enum.TryParse&lt;TEnum&gt;(value, out result))\n      return result;\n    return defaultValue;\n  }\n\n  public static TEnum Parse&lt;TEnum&gt;(ushort value)\n  {\n    return (TEnum)(object)value;\n  }\n\n  public static sbyte to_i1&lt;TEnum&gt;(TEnum value)\n  {\n    return (sbyte)(object)Convert.ChangeType(value, typeof(sbyte));\n  }\n\n  public static byte to_u1&lt;TEnum&gt;(TEnum value)\n  {\n    return (byte)(object)Convert.ChangeType(value, typeof(byte));\n  }\n\n  public static short to_i2&lt;TEnum&gt;(TEnum value)\n  {\n    return (short)(object)Convert.ChangeType(value, typeof(short));\n  }\n\n  public static ushort to_u2&lt;TEnum&gt;(TEnum value)\n  {\n    return (ushort)(object)Convert.ChangeType(value, typeof(ushort));\n  }\n\n  public static int to_i4&lt;TEnum&gt;(TEnum value)\n  {\n    return (int)(object)Convert.ChangeType(value, typeof(int));\n  }\n\n  public static uint to_u4&lt;TEnum&gt;(TEnum value)\n  {\n    return (uint)(object)Convert.ChangeType(value, typeof(uint));\n  }\n\n}\n</code></pre>\n\n<p>hope this helps someone.</p>\n'}, {'answer_id': 50289291, 'author': 'Ivan Ferić', 'author_id': 444634, 'author_profile': 'https://Stackoverflow.com/users/444634', 'pm_score': 5, 'selected': False, 'text': '<p>As of C# 7.3, there is now a built-in way to add enum constraints:</p>\n\n<pre><code>public class UsingEnum&lt;T&gt; where T : System.Enum { }\n</code></pre>\n\n<p>source: <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint" rel="noreferrer">https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint</a></p>\n'}, {'answer_id': 50411982, 'author': 'Mik', 'author_id': 1554208, 'author_profile': 'https://Stackoverflow.com/users/1554208', 'pm_score': 3, 'selected': False, 'text': '<p>As of C# 7.3, you can use the Enum constraint on generic types:</p>\n\n<pre><code>public static TEnum Parse&lt;TEnum&gt;(string value) where TEnum : Enum\n{\n    return (TEnum) Enum.Parse(typeof(TEnum), value);\n}\n</code></pre>\n\n<p>If you want to use a Nullable enum, you must leave the orginial struct constraint:</p>\n\n<pre><code>public static TEnum? TryParse&lt;TEnum&gt;(string value) where TEnum : struct, Enum\n{\n    if( Enum.TryParse(value, out TEnum res) )\n        return res;\n    else\n        return null;\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/7244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/905/']