Skip to content

Instantly share code, notes, and snippets.

@lmatt-bit
Created April 12, 2014 09:09
Show Gist options
  • Select an option

  • Save lmatt-bit/10526070 to your computer and use it in GitHub Desktop.

Select an option

Save lmatt-bit/10526070 to your computer and use it in GitHub Desktop.
Get or set value for a field with reflection
class RTest
{
public static int staticInt;
public int instantInt;
}
Type type = typeof(RTest);
var field = type.GetField("staticInt");
field.SetValue(null, 10);
Console.WirteLine(field.GetValue(null));//why use null here? because this is a static field
var obj = new RTest();
var field2 = type.GetField("instantInt");
field2.SetValue(obj, 11);
Console.WirteLine(field.GetValue(obj));//pay attention to the parameter.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment