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
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.
Using PropertyInfo to find out the type of the property and get its value
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
.
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.