Set the value of the field in CSharp
Description
The following code shows how to set the value of the field.
Example
using System;//from ww w . j a va2s. c o m
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(myFieldInfo.GetValue(myObject));
myFieldInfo.SetValue(myObject, "New value");
Console.WriteLine(myFieldInfo.GetValue(myObject));
}
}
The code above generates the following result.