Efrain
Efrain

Reputation: 3364

System.Reflection; Produce a List of Fields (of a certain Type)

I have a class which has a large number of static fields of a certain type, say Foo. In order to simplify and shorten code, I thought about putting them into an array (i.e. their references of course).

I can do that by simply writing out each field name explicitly and putting them into a List/Array.. (i.e. myList.Add(this.A)) .. but since I have plenty of those Fields and they change sometimes, I want do do it all through Reflection.. should be possible, no?

public class MyClass
{
    public static Foo A = new Foo(...);
    public static Foo B = new Foo(...);
    public static Foo C = new Foo(...);
    (...)

    public List<Foo> getFoos()
    {
        MemberInfo[] allFooFields = typeof(MyClass).GetFields();

        // Fill In Foo Fields into a List
        var listOfFooFields = new List<Foo>;

        // ???

        return listOfFooFields;
    }
}

Upvotes: 2

Views: 131

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174319

Use this:

public List<Foo> getFoos()
{
    return typeof(MyClass).GetFields(BindingFlags.Static | BindingFlags.Public)
                          .Where(x => x.FieldType == typeof(Foo))
                          .Select(x => x.GetValue(null))
                          .Cast<Foo>()
                          .ToList();
}

Upvotes: 4

Related Questions