CodeBlanks Logo Icon CodeBlanks

PropertyInfo GetValue/SetValue

C# course · Advanced · Lesson 47/83

Learn to read and write property values with PropertyInfo.

PropertyInfo GetValue/SetValue

PropertyInfo holds the metadata of a property. pi.GetValue(obj) reads the property value; pi.SetValue(obj, value) writes it. The value comes as object?.

This lets serializers and ORMs access properties without knowing their types. For example, a serializer calls GetValue for each property and writes the result to a text format. The same approach is used in code generators.

Indexed properties

For indexed properties, GetValue and SetValue take a second parameter: the index array. E.g. pi.GetValue(obj, new object[] { 0 }). This reads the first element of a list-like property.

Indexed properties are rare; for most regular properties GetValue(obj) and SetValue(obj, value) suffice. Serializers usually skip indexed properties because text-based formats expect plain key-value pairs.

Exercise Read and write a property value

In the Person class below, get the Name property with PropertyInfo pi = typeof(Person).GetProperty("Name");. Write a value with pi.SetValue(p, "Ayşe");. Read it with pi.GetValue(p) and print with Console.WriteLine.

Show example solution
Get the property with PropertyInfo pi = typeof(Person).GetProperty("Name");. Write the value with pi.SetValue(p, "Ayşe");. Read and print with Console.WriteLine(pi.GetValue(p));.
Example solution:
using System;
using System.Reflection;

class Person
{
    public string Name { get; set; } = "Initial";
}

class Program
{
    static void Main()
    {
        Person p = new Person();
        PropertyInfo pi = typeof(Person).GetProperty("Name");
        pi.SetValue(p, "Ayşe");
        Console.WriteLine(pi.GetValue(p));
    }
}

Test yourself

  1. Complete the GetValue call

    object val = pi.____(obj);
    Show answer
    object val = pi.GetValue(obj);
  2. How many parameters does SetValue take?

    • Only one (value)
    • Two (instance and value)
    • Three (instance, value and type)
    • None
    Show answer

    Two (instance and value) — Correct. SetValue takes two parameters: instance and value.

  3. Match the method to its action

    GetValue
    Reads
    SetValue
    Writes
    GetMethod
    Gets a method
    GetField
    Gets a field

All lessons in Advanced