aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Core/ExtensionMethods/EnumExtensions.cs
blob: 97256faa533a1e949bda853afb75cf763253d651 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

/// <summary>
/// Contains <see cref="Enum"/> extension methods.
/// </summary>
public static class EnumExtensions
{
    /// <summary>
    /// Gets the Enum description attribute value.
    /// </summary>
    /// <param name="value">The enum value.</param>
    /// <returns></returns>
    public static String ToDescription(this Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attributes != null &&
            attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }

    public static T GetAttribute<T>(this Enum value) where T : Attribute
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());
        return fi.GetCustomAttribute<T>();
    }

    /// <summary>
    /// Gets the enum integer value.
    /// </summary>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    public static int ToInt32(this Enum value)
    {
        return (int)((object)value);
    }

    /// <summary>
    /// Gets all the flags from a bitwise enumeration.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="input">The enum.</param>
    /// <returns></returns>
    public static IEnumerable<T> GetFlags<T>(this Enum input)
    {
        foreach (Enum value in Enum.GetValues(input.GetType()))
            if (input.HasFlag(value))
                yield return (T)(object)value;
    }
}