๐ŸŽ“ A1Learner
๐Ÿ”
0 of 28 lessons completed

C# Reflection Members

Reflection can read and write members through their information objects. A PropertyInfo or a FieldInfo acts on a target object passed to each call.

Reading and writing a property

GetProperty finds the Count property. GetValue reads it, SetValue changes it, and GetValue reads it again.

using System;
using System.Reflection;

class Meter
{
    public int Count { get; set; } = 5;
}

class Program
{
    static void Main(string[] args)
    {
        Meter meter = new Meter();
        PropertyInfo prop = typeof(Meter).GetProperty("Count");
        Console.WriteLine(prop.GetValue(meter));
        prop.SetValue(meter, 41);
        Console.WriteLine(prop.GetValue(meter));
    }
}

Reading and writing a field

GetField finds the public Mode field. The value starts as Heat and is replaced with Cold.

using System;
using System.Reflection;

class Dial
{
    public string Mode = "Heat";
}

class Program
{
    static void Main(string[] args)
    {
        Dial dial = new Dial();
        FieldInfo field = typeof(Dial).GetField("Mode");
        Console.WriteLine(field.GetValue(dial));
        field.SetValue(dial, "Cold");
        Console.WriteLine(field.GetValue(dial));
    }
}

Checking whether a property can be written

GetProperties returns the properties of Meter. The loop prints the CanWrite value for Count.

using System;
using System.Reflection;

class Meter
{
    public int Count { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        PropertyInfo[] props = typeof(Meter).GetProperties();
        foreach (PropertyInfo prop in props)
        {
            Console.WriteLine(prop.Name + " can write: " + prop.CanWrite);
        }
    }
}

Example

using System;
using System.Reflection;

class Thermostat
{
    public int Temp { get; set; } = 20;
}

class Program
{
    static void Main(string[] args)
    {
        Thermostat thermostat = new Thermostat();
        PropertyInfo prop = typeof(Thermostat).GetProperty("Temp");
        prop.SetValue(thermostat, 24);
        Console.WriteLine(prop.GetValue(thermostat));
        Console.WriteLine(thermostat.Temp);
    }
}

Key points

  • GetProperty returns the PropertyInfo for a named property.
  • GetValue reads a property value from a target object.
  • SetValue writes a new value to a property on a target object.
  • GetField returns the FieldInfo for a named field.
  • FieldInfo reads and writes field values with GetValue and SetValue.
  • GetProperties returns every public property, and CanWrite reports whether a property has a setter.

In this example, SetValue writes 24 into the Temp property. GetValue reads 24 back through reflection. A direct read of the property prints the same 24.

Note

Member names are passed as strings, so a wrong name fails at run time.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does PropertyInfo.SetValue need to change a property?