Use reflection to list a class’s fields in C#


Even though fields and properties are very similar when you interact with an item in code, to C# they are different. One side effect of that is that the GetProperties method provided by reflection lists only properties, not fields. Fortunately, the GetFields method works in a similar manner, although many of the details are different.

This example uses the following code to add some fields to the Form1 class.

// Add some fields.
private int MyPrivateField = 1;
public int MyPublicField = 2;
public static int MyPublicStaticField = 3;
public static int MyProtectedField = 4;
public const int MyConstField = 5;
public int[] MyArray = { 1, 2, 3, 4, 5 };
public int[] MyEmptyArray = { };
public int[] MyNullArray;

When the program’s form loads, the following code displays information about the class’s fields.

// List the fields.
// Use the class you want to study instead of Form1.
object property_value;
FieldInfo[] field_infos = typeof(Form1).GetFields(
    BindingFlags.FlattenHierarchy |
    BindingFlags.Instance |
    BindingFlags.NonPublic |
    BindingFlags.Public |
foreach (FieldInfo info in field_infos)
    string name = info.Name;
    string attributes = info.FieldType.Attributes.ToString();

    string visibility = "";
    if (info.IsAssembly) visibility += " assembly";
    if (info.IsFamily) visibility += " family";
    if (info.IsFamilyAndAssembly)
        visibility += " family AND assembly";
    if (info.IsFamilyOrAssembly)
        visibility += " family OR assembly";
    if (info.IsInitOnly) visibility += " init";
    if (info.IsLiteral) visibility += " literal";
    if (info.IsPrivate) visibility += " private";
    if (info.IsPublic) visibility += " public";
    if (info.IsStatic) visibility += " static";
    if (visibility.Length > 0)
        visibility = visibility.Substring(1);

    string value = "";

    // See if it's an array.
    if (!info.FieldType.IsArray)
        // It's not an array.
        property_value = info.GetValue(this);
        if (property_value == null)
            value = "<null>";
            value = property_value.ToString();
        // It is an array.
        name += "[]";
        // If it's an array of integers, get the values.
        if (info.FieldType.Name == "Int32[]")
            Int32[] values = (Int32[])info.GetValue(this);
            if (values == null)
                value = "<null>";
                foreach (Int32 val in values)
                    value += ", " + val.ToString();
                if (value.Length > 0) value = value.Substring(2);
                value = "[" + value + "]";
            value = "<array>";

    ListViewMakeRow(lvwProperties, name,
        attributes, visibility, value);

The code gets the Form1 type and calls its GetFields method to get information about the class’s fields. See the example Use reflection to list a class’s properties in C# for information about the BindingFlags parameters.

The code then loops through the FieldInfo objects that GetFields returns. The code uses the FieldInfo object’s Name property to get the field’s name. It uses the object’s FieldType.Attributes property to get information about the field’s attributes.

Next, the code checks a series of FieldInfo properties to get information about the field’s accessibility and build a string describing the values.

The code then uses methods similar to those used by the earlier example to display the field’s value. This example also shows how to show the values in an integer array. If the field’s type name is Int32[] and the code can get its value, then the program loops through the field’s value (which is an array) and adds its entries to a string.

The code finishes by calling the ListViewMakeRow method to display the information in the form’s ListView control. Download the example program to see how that works.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in reflection and tagged , , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Use reflection to list a class’s fields in C#

  1. Pingback: Use reflection to list the fields provided by the SystemInformation class in C# - C# HelperC# Helper

  2. Prechtl says:

    Pascal was a teaching language originally run on mainframes. Novice programmers are more likely to miss differences in values during subtraction leading to problems with unsigned integers. The iron is big and the easy solution is to go with the next larger step of signed integer. Conversely, the memory limits on early micros made larger programs (i.e. not class work) using 32 bit signed integers everywhere impractical. Some system return the actual allocated memory or -1 for failure. With signed integers and a system that can only use half the possible addresses for program allocation, that works perfectly. In practice, that just leads to rediscovering Bell”s axiom: “There is only one mistake that can be made in a computer design that is difficult to recover fromnot providing enough address bits for memory addressing and memory management. Slow floppies, such luxury. Want to know painful development, try a paper tape compiler. Fortran II on a PDP-8 equipped with paper tape attached to a teletype as the only storage is an interesting experience but not one anyone wishes to try more than once.

Comments are closed.