Hello Guest

Author Topic: Enum Extensions  (Read 1725 times)

0 Members and 1 Guest are viewing this topic.

Fruckert

  • Member
  • Posts: 60
  • Total Square
    • View Profile
Enum Extensions
« on: February 08, 2015, 01:20:37 PM »
I noticed that an enum extension was added, and I happen to have a full suite of them in my personal utility library.
Code: [Select]
#region Enum Extensions
//http://hugoware.net/blog/enums-flags-and-csharp
public static bool Has<T>(this Enum type, T value)
{
    try
    {
        return (((int)(object)type & (int)(object)value) == (int)(object)value);
    }
    catch
    {
        return false;
    }
}

public static bool Is<T>(this Enum type, T value)
{
    try
    {
        return (int)(object)type == (int)(object)value;
    }
    catch
    {
        return false;
    }
}


public static T Add<T>(this Enum type, T value)
{
    try
    {
        return (T)(object)(((int)(object)type | (int)(object)value));
    }
    catch (Exception ex)
    {
        throw new ArgumentException(
            string.Format(
                "Could not append value from enumerated type '{0}'.",
                typeof(T).Name
                ), ex);
    }
}


public static T Remove<T>(this Enum type, T value)
{
    try
    {
        return (T)(object)(((int)(object)type & ~(int)(object)value));
    }
    catch (Exception ex)
    {
        throw new ArgumentException(
            string.Format(
                "Could not remove value from enumerated type '{0}'.",
                typeof(T).Name
                ), ex);
    }
}
#endregion

They're originally from here and I found them on Stack Overflow here, and although they're a bit aged and do a lot of casting weirdness, I've found them to work really well. I've used them for powerups and the like in some prototypes.
« Last Edit: February 08, 2015, 01:22:38 PM by Fruckert »

Kyle

  • Administrator
  • Member
  • Posts: 258
    • View Profile
Re: Enum Extensions
« Reply #1 on: February 08, 2015, 03:42:11 PM »
Cool!  Always nice to have more extensions (I think!) I'll take a look through these to see if I want to add any.