Skip to content

Instantly share code, notes, and snippets.

@tdewilde
tdewilde / GetEnumDictionary<T>()
Created April 7, 2014 08:26
Convert an Enum to a Dictionary<int, string>. Uses the extension method Enum.GetDescription() to retrieve the value.
public static Dictionary<int, string> GetEnumDictionary<T>() where T : struct
{
if (!typeof(T).IsEnum)
throw new ArgumentException("T is not an Enum type");
return Enum.GetValues(typeof(T))
.Cast<object>()
.ToDictionary(k => (int)k, v => ((Enum)v).GetDescription());
}
@tdewilde
tdewilde / Enum.GetDescription()
Created April 7, 2014 08:23
Extension method to get the Description value from an Enum. If not present, return Enum name.
public static string GetDescription(this Enum enumeration)
{
string value = enumeration.ToString();
Type enumType = enumeration.GetType();
var descAttribute = (DescriptionAttribute[])enumType
.GetField(value)
.GetCustomAttributes(typeof(DescriptionAttribute), false);
return descAttribute.Length > 0 ? descAttribute[0].Description : value;
}
@tdewilde
tdewilde / Control.AllChildControls()
Created January 9, 2014 10:02
Get all child controls for a certain control.
public static IEnumerable<Control> AllChildControls(this Control control)
{
var children = control.Controls.Cast<Control>();
return children.SelectMany(c => AllChildControls(c)).Concat(children);
}
@tdewilde
tdewilde / DateTime.IsLastDayOfTheMonth()
Last active December 31, 2015 05:29
Extension method to determine whether the given date is the last day of the month.
public static bool IsLastDayOfTheMonth(this DateTime dateTime)
{
return dateTime.Month != dateTime.AddDays(1).Month;
}
@tdewilde
tdewilde / Int32.ToGuid()
Last active December 17, 2015 20:48
Extension method to convert an integer to a Guid. Useful for mocking objects in a unit test.
public static Guid ToGuid(this int value)
{
byte[] bytes = new byte[16];
BitConverter.GetBytes(value).CopyTo(bytes, 0);
return new Guid(bytes);
}