/// <summary> /// Splits a flags enum value into its atmoic flags and returns them as an IEnumerable of integers. /// </summary> /// <param name="source">The combination of bitflags to split up.</param> /// <returns>An IEnumerable of integers that contains the integer representation of the bitflags set in <paramref name="source"/>.</returns> public static IEnumerable <int> GetAtomicFlags(this Enum source) { source.AssertNotNull(nameof(source)); int numFlags = Convert.ToInt32(source); for (int currentFlag = 1; numFlags != 0; currentFlag = currentFlag << 1) { if ((numFlags & currentFlag) == currentFlag) { yield return(currentFlag); numFlags ^= currentFlag; } } }
/// <summary> /// Maps the specified source value to a given enumeration type by the Name of the enumeration value. /// The source is passed as an <see cref="Enum"/> to avoid requiring both types to be specified. /// </summary> /// <typeparam name="TEnumTarget">The type of the enumeration target.</typeparam> /// <param name="source">The source.</param> /// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentException"> /// <paramref name="source"/> does not exist on the target enumeration. /// </exception> /// <returns>An enumeration value of the specified target type.</returns> public static TEnumTarget Map <TEnumTarget>(Enum source) where TEnumTarget : struct { source.AssertNotNull("source"); var value = source.ToString(); TEnumTarget result; if (!Enum.TryParse <TEnumTarget>(value, out result)) { throw new ArgumentException( string.Format( "The value '{0}' does not exist on the '{1}' enumeration.", value, typeof(TEnumTarget).FullName), "source"); } return(result); }