Skip to content

Instantly share code, notes, and snippets.

@liortal53
Created September 16, 2022 06:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liortal53/d4a4881a0a7bbf216099c1a81536f5f6 to your computer and use it in GitHub Desktop.
Save liortal53/d4a4881a0a7bbf216099c1a81536f5f6 to your computer and use it in GitHub Desktop.
EnumExtensions Example
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