Created
September 16, 2022 06:01
-
-
Save liortal53/d4a4881a0a7bbf216099c1a81536f5f6 to your computer and use it in GitHub Desktop.
EnumExtensions Example
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
using System; | |
using System.Linq; | |
[Flags] | |
public enum Enemy | |
{ | |
None = 0, | |
Goblin = 1, | |
Wizard = 2, | |
Dragon = 4 | |
} | |
public static class EnumExtensions | |
{ | |
// Returns true if the given enum 'e' has *ANY* of the passed options | |
public static bool Has(this Enum e, params Enum[] options) | |
{ | |
return options.Any(o => e.HasFlag(o)); | |
} | |
// Returns true if the given enum 'e' doesn't have *ANY* of the passed options | |
public static bool DoesntHave(this Enum e, params Enum[] options) | |
{ | |
return Has(e, options) == false; | |
} | |
} | |
public class Program | |
{ | |
public static void Main() | |
{ | |
Enemy enemy = Enemy.Dragon; | |
var result1 = enemy.Has(Enemy.Wizard, Enemy.Dragon); // returns true | |
var result2 = enemy.Has(Enemy.Goblin); // returns false | |
var result3 = enemy.DoesntHave(Enemy.Goblin); // returns true | |
Console.WriteLine(result1 + " " + result2 + " " + result3); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment