Daniel Daniel - 1 month ago 7
C# Question

How to iterate all static public Guids in static class

Given is my sample class:

public static class MyConstantClass
{
public static readonly Guid Prop1 = new Guid("d0f6f396-b75e-4312-bb54-09fbb40cf51e");
public static readonly Guid Prop2 = new Guid("398810e5-1ed2-468c-9f21-1af58dcecbbf");
}


what i have tried so far:

var props= typeof(MyConstantClass).GetProperties(BindingFlags.Public |
BindingFlags.Static |
BindingFlags.FlattenHierarchy)
.ToList();


But this returns an empty list.

Answer

Your mistake is that these Guids aren't properties but just fields of the class:

var props = typeof(MyConstantClass).GetFields(BindingFlags.Public | 
                                              BindingFlags.Static |
                                              BindingFlags.FlattenHierarchy)
                                   .ToList();

To use the GetProperties define your class as such:

public static class MyConstantClass
{
    public static Guid Prop1 { get; } = new Guid("d0f6f396-b75e-4312-bb54-09fbb40cf51e");
    public static Guid Prop2 { get; } = new Guid("398810e5-1ed2-468c-9f21-1af58dcecbbf");
}