TheDeveloperBlog.com


C# SetValue Reflection Method: FieldInfo

SetValue accesses fields by their names. With the System.Reflection namespace methods, we can take a string that represents a target field, and then change the actual value of that field. We demonstrate how to use SetValue on fields.


Example. First, this program has a public static int field with the identifier _field. We get the type of the class using the typeof operator. Then we call GetField with the string literal "_field" as the argument.

String Literal

Finally: We invoke the SetValue field with a null first argument and an integer value as the second argument.

typeof
C# program that uses SetValue on FieldInfo

using System;
using System.Reflection;

class Program
{
    public static int _field; // Must be public!

    static void Main()
    {
	// Get FieldInfo on Program type.
	FieldInfo info = typeof(Program).GetField("_field");

	// Set static field to this value.
	info.SetValue(null, 1969);

	// Now see what _field equals.
	Console.WriteLine(_field);
    }
}

Output

1969

The first argument to the SetValue method is the object instance you want to mutate. If you are using a static field, though, this can be left as null. It might make more sense for the .NET Framework to provide a SetValueStatic method.

Null

Summary. The SetValue method is present on several reflection constructs. These include PropertyInfo and FieldInfo. Conceptually, this method changes the value of an actual part of memory based on a reflected object.

And: It bridges the gap between reading the metadata as reflected information and mutating the actual program's memory.

Reflection Field