Enum HasFlag method extension for < 4.0 Framework

In the same idea than the previous article, here is an extension method to mimic the 4.0 HasFlag method (http://msdn.microsoft.com/en-us/library/system.enum.hasflag.aspx).

     /// <summary>
    /// Extentions for enums.
    /// </summary>
    public static class EnumExtensions
    {
        /// <summary>
        /// A FX 3.5 way to mimic the FX4 "HasFlag" method.
        /// </summary>
        /// <param name="variable">The tested enum.</param>
        /// <param name="value">The value to test.</param>
        /// <returns>True if the flag is set. Otherwise false.</returns>
        public static bool HasFlag(this Enum variable, Enum value)
        {
            // check if from the same type.
            if (variable.GetType() != value.GetType())
            {
                throw new ArgumentException("The checked flag is not from the same type as the checked variable.");
            }

            ulong num = Convert.ToUInt64(value);
            ulong num2 = Convert.ToUInt64(variable);

            return (num2 & num) == num;
        }
    }

Incoming search terms:

  • enum hasflag
  • EnumHasFlagmethodextensionfor<4 0Framework
  • c# hasflag
  • Enum HasFlag 3 5
  • hasflag net 3 5
  • enum hasflag c# 3 5
  • HasFlag 3 5
  • C# enum Hasflag
  • C# hasflag net3 5
  • windows phone 7 enum hasflag

2 comments

  1. admin says:

    good point ;)
    I removed this extra line now

  2. Barrett says:

    Line 20?
    :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>