.NET 4.0: Enum.HasFlag is not what you might expect... menu

User Tag List

Results 1 to 1 of 1
  1. #1
    XTZGZoReX's Avatar Active Member
    Reputation
    32
    Join Date
    Apr 2008
    Posts
    173
    Thanks G/R
    0/0
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    .NET 4.0: Enum.HasFlag is not what you might expect...

    (From post: .NET 4.0: Enum Base Type )

    In .NET 4.0, we’re apparently allowed to freely extend the base type for all enumerations – Enum. This wasn’t previously possible, as the class was regarded static.

    As some people might’ve discovered through funny behavior of their programs after switching to .NET 4.0, Enum.HasFlag does NOT return true if the enum value has any of the flags; only if it has ALL of them. The beta of .NET 4.0 didn't act like this, but the release version does.

    However, given that we’re now allowed to extend the Enum type, we can simply do the following:

    Code:
    public static bool HasAnyFlag(this Enum value, Enum toTest)
    {
        var val = ((IConvertible)value).ToUInt64(null);
        var test = ((IConvertible)toTest).ToUInt64(null);
    
        return (val & test) != 0;
    }
    (Note: There's a valid reason for the UInt64 casts; that is genericness. This method will work on an enum of any base type (Byte, UInt16, UInt32, UInt64, etc).)

    This will do what you might’ve originally expected from Enum.HasFlag.

    This change appears to be undocumented. At least, I can’t find any MSDN page mentioning that the Enum type can now be used and extended freely.

    Of course, with the Enum type now being usable as a variable type, you can extend it much much further than previously possible.

    Thanks to Domi for this - he tried compiling a piece of code that extended the Enum type, which turned out to be working, making for this post.

    .NET 4.0: Enum.HasFlag is not what you might expect...

Similar Threads

  1. Identifying 100 legendaries, what you can expect!
    By Samztwitch in forum Diablo 3 General
    Replies: 10
    Last Post: 05-28-2014, 03:22 AM
  2. Hearthstone Booster Pack Breakdown: This is what you can expect per pack!
    By ArBar in forum Hearthstone: Heroes of Warcraft
    Replies: 10
    Last Post: 03-22-2014, 05:52 AM
  3. [Selling] KHAccounts.net -- Now Accepting Credit/Check Cards NOT Through Paypal!
    By KHAccounts in forum WoW-US Account Buy Sell Trade
    Replies: 0
    Last Post: 08-18-2012, 09:29 PM
  4. What You Should and Should NOT Post In This Section
    By Dragonshadow in forum World of Warcraft Guides
    Replies: 17
    Last Post: 06-07-2009, 02:35 AM
All times are GMT -5. The time now is 12:09 PM. Powered by vBulletin® Version 4.2.3
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved. User Alert System provided by Advanced User Tagging (Pro) - vBulletin Mods & Addons Copyright © 2024 DragonByte Technologies Ltd.
Digital Point modules: Sphinx-based search