Mega Code Archive

 
Categories / C# / Reflection
 

Sets the value of the field supported by the given object

using System; using System.Reflection; using System.Globalization; public class Example {     private string myString;     public Example()     {         myString = "Old value";     }     public string StringProperty     {         get         {             return myString;         }     } } public class FieldInfo_SetValue {     public static void Main()     {         Example myObject = new Example();         Type myType = typeof(Example);         FieldInfo myFieldInfo = myType.GetField("myString", BindingFlags.NonPublic | BindingFlags.Instance);          Console.WriteLine( "\nThe field value of myString is \"{0}\".", myFieldInfo.GetValue(myObject));          myFieldInfo.SetValue(myObject, "New value");          Console.WriteLine( "The field value of mystring is \"{0}\".", myFieldInfo.GetValue(myObject));     } }