Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through properties of static class to populate list?

I have a class of string constants, how can I loop through to get the string and populate a list-box?

static class Fields
{
    static readonly string FirstName = "FirstName";
    static readonly string LastName = "LastName";
    static readonly string Grade = "Grade";
    static readonly string StudentID1 = "StudentID";
    static readonly string StudentID2 = "SASINumber";
}

public partial class SchoolSelect : Form
{
    public SchoolSelect()
    {
        InitializeComponent();

        //SNIP

        // populate fields
        //Fields myFields = new Fields(); // <-- Cant do this
        i = 0;
        foreach (string field in Fields) // ???
        { 
            fieldsBox.Items.Insert(i, Fields ???
        }
    }

I can't create a new instance of Fields because its a static class. How can I get all the fields into the list-box without manually inserting each one?

like image 590
pdizz Avatar asked Sep 18 '12 15:09

pdizz


1 Answers

try Reflection with somethin like this:

(UPDATED VERSION)

        Type type = typeof(Fields); // MyClass is static class with static properties
        foreach (var p in type.GetFields( System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic))
        {
            var v = p.GetValue(null); // static classes cannot be instanced, so use null...
            //do something with v
            Console.WriteLine(v.ToString());
        }
like image 79
Cybermaxs Avatar answered Oct 22 '22 16:10

Cybermaxs