Convert a class of static fields to a dictionary in C#
I was coding in a C# project when I came across a class that was mapping names to GUIDs. Since GUIDs are objects, you can't simply put them in a const array or an enum like you can do with simpler data types.
public static class Guids
{
public static readonly Guid First = new Guid("F288114A-B29E-40A2-B649-DF87B10B8E7C");
public static readonly Guid Second = new Guid("AFE63E51-A611-426C-8226-4A98A93195DB");
public static readonly Guid Third = new Guid("02CFDDDE-5C0E-4E65-B756-25DB72A08503");
public static readonly Guid Fourth = new Guid("500CDF93-D1D1-4A89-A348-5A1B5265B1FA");
public static readonly Guid Fifth = new Guid("890CD9E4-59B7-4C9B-95BF-9FFC159E169E");
}
If I was trying to look up a GUID by name, it would be as easy as accessing the object by the name, but I had a GUID and wanted to get the same for it.
The approach I took was to create a dictionary where the GUID values were the keys and the names were the values. Using the GetFields() method on the type of the object seemed like best way to get the public properties. I could then use LINQ to convert this list of fields to the data structure I needed.