Last active
October 20, 2018 11:55
-
-
Save cortvi/0fd14cf6d2eb9a7a732a9c5155ed2ea9 to your computer and use it in GitHub Desktop.
Flag enums extension methods for Unity (if using .NET 3.5 or less)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Created by @cortvi | |
/// adapted code from: | |
/// https://stackoverflow.com/questions/28167873/custom-generic-setflag-unsetflag-extension-methods | |
using System; | |
using System.Globalization; | |
public static class Extension | |
{ | |
/// <summary> | |
/// Usage: "if ( someEnum.HasFlag (someEnumFlag) ) {..}" | |
/// </summary> | |
public static bool HasFlag<T> ( this T e, T flag ) where T : struct, IConvertible | |
{ | |
var value = e.ToInt32(CultureInfo.InvariantCulture); | |
var target = flag.ToInt32(CultureInfo.InvariantCulture); | |
return ((value & target) == target); | |
} | |
/// <summary> | |
/// Usage: "someEnum = someEnum.SetFlag (someEnumFlag);" | |
/// </summary> | |
public static T SetFlag<T> (this T e, T flag) where T : struct, IConvertible | |
{ | |
var value = e.ToInt32(CultureInfo.InvariantCulture); | |
var newFlag = flag.ToInt32(CultureInfo.InvariantCulture); | |
return (T)(object)(value | newFlag); | |
} | |
/// <summary> | |
/// Usage: "someEnum = someEnum.UnsetFlag (someEnumFlag);" | |
/// </summary> | |
public static T UnsetFlag<T> (this T en, T flag) where T : struct, IConvertible | |
{ | |
int value = en.ToInt32(CultureInfo.InvariantCulture); | |
int newFlag = flag.ToInt32(CultureInfo.InvariantCulture); | |
return (T)(object)(value & ~newFlag); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment