Skip to content

Instantly share code, notes, and snippets.

@binary1230
Created October 3, 2020 12:53
Show Gist options
  • Save binary1230/0f7e0642d84ff4ddbdc474c78d057b7d to your computer and use it in GitHub Desktop.
Save binary1230/0f7e0642d84ff4ddbdc474c78d057b7d to your computer and use it in GitHub Desktop.
Dom's misc utils for C# databinding/enums/etc. Maybe not the best.
// just some quick snippets for GUI / Winforms / C# / etc
// these might not be the best ways to do this stuff, was just working on some ideas
// example of an enum with Description() applied
public enum ROMMapMode : byte
{
LoROM,
HiROM,
ExHiROM,
[Description("SA - 1 ROM")]
SA1ROM,
[Description("SA-1 ROM (FuSoYa's 8MB mapper)")]
ExSA1ROM,
SuperFX,
[Description("Super MMC")]
SuperMMC,
ExLoROM
}
// take a enum type that has [Description] attributes,
// return a List with with kvp pairs of enum vs description
public static List<KeyValuePair<TEnum, string>>
GetEnumDescriptions<TEnum>() where TEnum : Enum
{
var type = typeof(TEnum);
return Enum.GetValues(type)
.Cast<TEnum>()
.Select(value => new
KeyValuePair<TEnum, string>(key: value, value: GetEnumDescription(value))
)
.OrderBy(item => item.Key)
.ToList();
}
public class EnumMapper<TEnum> where TEnum : Enum
{
public TEnum Source { get; set; }
// surely... there is some third party library that handles this.
// for now, here we are.
public int SelectedIndex
{
get => Convert.ToInt32(Source);
set => Source = (TEnum)Enum.ToObject(typeof(TEnum), value);
}
public List<KeyValuePair<TEnum, string>> Descriptions { get; }
= Util.GetEnumDescriptions<TEnum>();
}
var mapper = new EnumMapper<Data.ROMMapMode>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment