A list of my favorite C# examples using Reflection

This article contains a list of code lines, that use reflection to access data in classes. Reflection can be combined with Generics and even though some might think it can be hacky, I find that Reflection offers a tremendous advantage when dealing with monolithic application and you want to write reusable code, and you can not use object oriented concepts such as inheritance. Let’s start without further delay.

Detect if a class property is a reference or a value type

For detecting if a property of a class is a reference type is to use the IsClass Property on each property of a class to find out

1
2
3
4
5
6
7
foreach( PropertyInfo propertyInfo in TestClass.GetType().GetProperties())
{
     if (propertyInfo.PropertyType.IsClass && propertyInfo.PropertyType != typeof(string)) 
     {
        // The property is a reference type.
     }
}

Be aware that for string type the IsClass property returns true.

More information can be found on this StackOverflow question.

Iterate through the properties of a class

Imagine working on a monolithic application and extracting common properties of different classes into a base class is not an easy option. One way to treat these classes as common is to parse their common properties, which they have almost identical names, with reflection. So you will search for a property containing a specific string.

1
2
3
4
5
6
7
8
9
10
Person person = new();

PropertyInfo[] properties = typeof(Person).GetProperties();
foreach (PropertyInfo property in properties)
{
    if (property.Name == "foo")
    {
        // Do something
    }
}

Using PropertyInfo to find out the type of the property and get its value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public bool ValidateData(object data)
{
    foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
    {
        // Find the type with PropertyType
        if (propertyInfo.PropertyType == typeof(string))
        {
            // Get the value of the property with GetValue
            string value = propertyInfo.GetValue(data, null);

            // Do something with the value
        }
    }            

    return true;
}

More information can be found on this StackOverflow question.

Access an object property by its name and get its value

Analogue to the first example, here is one I used with EndsWith.

1
object detailsObj = parentObj?.GetType().GetRuntimeProperties().First(p => p.Name.EndsWith("Details")).GetValue(parentObj);

Recursively get property and child properties of a class

Finally a more complex example is to get all the properties and their values of all class that are referenced. The code for that can be found on this StackOverflow question.

comments powered by Disqus