TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# SetValue Reflection Method: FieldInfo

This C# article shows how to use the SetValue method from System.Reflection.

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


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf