Getting a list of constants using Reflection

Thanks to Drew Marsh I was able to create a function to get a list of the constants for a particular type in c#.  There were two key things I was missing:
BindingFlags.FlattenHierarchy
Specifies that static members up the hierarchy should be returned. Static members include fields, methods, events, and properties. Nested types are not returned (More on BindingFlags)
IsInitOnly property of a FieldInfo
Gets a value indicating whether the field can only be set in the body of the constructor.(More Info)

Anyway here is the function:

/// <SUMMARY>
/// This method will return all the constants from a particular
/// type including the constants from all the base types
/// </SUMMARY>
/// <PARAM NAME="TYPE">type to get the constants for</PARAM>
/// <RETURNS>array of FieldInfos for all the constants</RETURNS>
private FieldInfo[] GetConstants(System.Type type)
{
    ArrayList constants = new ArrayList();

    FieldInfo[] fieldInfos = type.GetFields(
        // Gets all public and static fields

        BindingFlags.Public | BindingFlags.Static | 
        // This tells it to get the fields from all base types as well

        BindingFlags.FlattenHierarchy);

    // Go through the list and only pick out the constants
    foreach(FieldInfo fi in fieldInfos)
        // IsLiteral determines if its value is written at 
        //   compile time and not changeable
        // IsInitOnly determine if the field can be set 
        //   in the body of the constructor
        // for C# a field which is readonly keyword would have both true 
        //   but a const field would have only IsLiteral equal to true
        if(fi.IsLiteral && !fi.IsInitOnly)
            constants.Add(fi);           

    // Return an array of FieldInfos
    return (FieldInfo[])constants.ToArray(typeof(FieldInfo));
}
PS: Code colorized by a codehtmler that Shawn A Van Ness and I are working, you will see more information about that soon.

7 Comments

Comments have been disabled for this content.