C# Reflection Field Example

by Sam Allen - Updated January 7, 2010

You have a class with instance or static fields of any type in the C# programming language and want to loop through those fields and display their names and values. The System.Reflection namespace in the .NET Framework provides a powerful and maintainable way to enumerate fields and properties in the C# language. Here we look at how you can loop through fields using reflection in the C# language, using the typeof expression and the GetFields method, followed by a foreach-loop construct.

Using GetFields

First, in the .NET Framework, every program is compiled into an assembly containing metadata, which is an abstract binary representation of the program's structure. This improves the options you have when executing your program, as you can explore the string data stored in the executable to access field and property names. This example demonstrates a static class with four fields of type Int32 and String. It obtains the FieldInfo objects for those fields and then displays them in a public method.

--- Program that uses reflection on fields (C#) ---

using System;
using System.Reflection;

static class ReflectionTest
{
    public static int Height;
    public static int Width;
    public static int Weight;
    public static string Name;

    public static void Write()
    {
        Type type = typeof(ReflectionTest); // Get type pointer
        FieldInfo[] fields = type.GetFields(); // Obtain all fields
        foreach (var field in fields) // Loop through fields
        {
            string name = field.Name; // Get string name
            object temp = field.GetValue(null); // Get value
            if (temp is int) // See if it is an integer.
            {
                int value = (int)temp;
                Console.Write(name);
                Console.Write(" (int) = ");
                Console.WriteLine(value);
            }
            else if (temp is string) // See if it is a string.
            {
                string value = temp as string;
                Console.Write(name);
                Console.Write(" (string) = ");
                Console.WriteLine(value);
            }
        }
    }
}

class Program
{
    static void Main()
    {
        ReflectionTest.Height = 100; // Set value
        ReflectionTest.Width = 50; // Set value
        ReflectionTest.Weight = 300; // Set value
        ReflectionTest.Name = "Perl"; // Set value
        ReflectionTest.Write(); // Invoke reflection methods
    }
}

--- Output of the program ---

Height (int) = 100
Width (int) = 50
Weight (int) = 300
Name (string) = Perl

Overview of program text. This program defines two classes and two methods. The program begins in the Main entry point and the static fields Height, Width, Weight, and Name are assigned on the ReflectionTest static class. Next, the Write method is invoked, which internally calls the typeof operator, the GetFields parameterless instance method, and then accesses the Name and GetValue members on each individual FieldInfo.

GetValue method and casting. The syntax used in the ReflectionTest.Write method when calling the GetValue instance method is confusing. In the example, the parameter call be the null literal because it is not used. There may be more elegant ways to obtain the value of a field or property, including adding extension methods.

Global variables class

Here we note one way you can use the reflection field logic as shown in this article. Many programs must maintain a set of preference values that are assigned during startup or later execution. You can store these preferences in an array, but this requires array lookups and possible bugs resulting from that. You can instead loop through fields with reflection and print their values to the console or web page. This approach improves performance when assigning or reading the values (because they are fields), but is not fast when reflecting the metadata to the screen. You can find more on global variables on this site.

(See Global Variable Use.)

Field instructions

Here we mention that when you use fields and assign or read them (as with the stsfld or ldsfld opcodes) you are creating exception-free code. The runtime documentation states that reading fields, because it does not invoke executable code, will not throw exceptions. This means that you can replace arrays or other collections with fields to improve reliability.

Summary

Here we looked at how you can invoke the methods in the System.Reflection namespace to enumerate the fields in a class using the C# programming language. We examined the syntax and used the typeof operator, the GetFields method, the FieldInfo class, and then the Name and GetValue members, finally casting the values from object before displaying them. We also noted issues related to fields in the metadata, such as using global variables and the exception guarantees in the .NET Framework relating to fields.

(Do not copy this page.)

Dot Net Perls | Search
Language | DllImport and Dllexport for DLL Interop | Global Variable Use | Process.Start Command-Line Examples | Timer Tutorial | WebClient Tutorial
C# | Decrement Int | HTML Brackets | Parameter Optimization Tip | SaveFileDialog Tutorial
© 2010 Sam Allen. All rights reserved.
Dot Net Perls | Sam Allen