Reminder to self (as I keep forgetting how versatile extension methods can be):
[WayBack] Mark Pintar sur Twitter : “The nice thing about extension methods is one can add it to most types. Even works of int, float and other primitive types… “
An interesting way of allowing methods on enumerated types is by using extension methods: [WayBack] Unity sample MonoBehaviour explaining how to associate simple strings with enums. · GitHub.
A more elaborate example from [WayBack] NoraGrace-Chess/Position.cs at master · ericoldre/NoraGrace-Chess · GitHub is below the fold.
Via:
- [WayBack] Freya Holmér on Twitter: “Did you know enum types support functions in C#? It’s a neat little trick using extension methods~✨ #unity3d #unitytips… “
- [WayBack] Eric Oldre on Twitter: „I used this technique EXTENSIVELY when developing my C# chess engine for representing positions, ranks, files, players, etc with type safety. (instead of ints)…“
- all from this great thread[WayBack] Freya Holmér on Twitter: “Did you know enum types support functions in C#? It’s a neat little trick using extension methods~✨ #unity3d #unitytips… “
using System; using System.ComponentModel; using UnityEngine; public class EnumDescription : MonoBehaviour { public enum PlayerState { Unknown, [Description("Alive and kicking")] Alive, [Description("Dead as a duck")] Dead } // Start is called before the first frame update void Start() { var state = PlayerState.Dead; Debug.Log("Player is " + state.GetDescription()); } } public static class EnumExtensions { public static string GetDescription(this Enum value) { var type = value.GetType(); var name = Enum.GetName(type, value); if (name != null) { var field = type.GetField(name); if (field != null) { if (Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attr) return attr.Description; } } return name; } }