Loop through constant members of a class

A little late but wouldn't this be a better solution?

http://weblogs.asp.net/whaggard/archive/2003/02/20/2708.aspx

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));
}

If you need the names you can do

fi.GetValue(null)

inside the loop.


You could implement a method that yields the strings:

public Ienumerable<string> GetStrings(){
   yield return TestA;
   yield return TestB;
}

Else you should look into reflection to return the properties that are static and string and then get the values by calling them.

Regards GJ


You could use reflection to loop through all the properties:

public DropDownItemCollection TestCollection
{
    var collection = new DropDownItemCollection();
    var instance = new TestClass();
    foreach (var prop in typeof(TestClass).GetProperties())
    {
        if (prop.CanRead)
        {
            var value = prop.GetValue(instance, null) as string;
            var item = new DropDownItem();
            item.Description = value;
            item.Value = value;
            collection.Add(item);
        }
    }
    return collection;
}

I just had the same challenge; to get all constants of my class (not properties!). Based on the most popular answer (for properties) and John's answer (for constants) I wrote this. I tested it and it works well.

private List<string> lstOfConstants= new List<string>();
    foreach (var constant in typeof(TestClass).GetFields())
    {
        if (constant.IsLiteral && !constant.IsInitOnly)
        {
            lstOfConstants.Add((string)constant.GetValue(null));
        }
    }

Tags:

C#

Class