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.
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;
}
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);