C#: .NET: Reflection

.NET Array Collections File String Async Cast DataTable DateTime Dictionary Enum Exception For Foreach IEnumerable If IndexOf Lambda LINQ List Parse Path Process Property Regex Replace Sort Split StringBuilder Substring Switch Tuple


With reflection we load field values. We loop through those fields and display their names and values.
in the .NET Framework,
provides a way to enumerate fields
and properties. It can access fields by name.


In the .NET Framework, every program is compiled into an assembly containing metadata. This is an abstract binary representation of the program's structure. This improves the options you have when executing your program.

And:You can explore the string data stored in the executable to access field and property names.

Framework: NET

Next:This static class has four fields of type Int32 and String. We get the FieldInfo objects for those fields and then display them.

Static ClassInt Type
C# program that uses reflection on fields

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(" (int) = ");
	    else if (temp is string) // See if it is a string.
		string value = temp as string;
		Console.Write(" (string) = ");

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


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

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. This 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.


Note:There may be more elegant ways to obtain the value of a field or property, including adding extension methods.

Extension Method


Class shapes

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.


Instead:You can loop through fields with reflection and print their values to the console or web page.

Also, 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.

Global VariableAbstract squares

Field instructions. When you use fields (as with stsfld or ldsfld) you are creating exception-free code. The runtime documentation states that reading fields, because it does not invoke executable code, will not throw exceptions.

IL: stsfld, ldsfld

Therefore:You can replace arrays or other collections with fields to improve reliability.


We invoked the methods in the System.Reflection namespace to enumerate the fields in a class. We examined the syntax and used the typeof operator, the GetFields method, the FieldInfo class, and then the Name and GetValue members.