The article demonstrates how to use reflection in C# and provides examples of how it can be used. Additionally, you can find information about TypeScript with an example.
About Reflection in C#
You can dynamically construct an instance of a type and bind it to an existing object using reflection in C#, as well as you can get the type from an existing object and invoke its methods or access its fields and properties using reflection. And also, it allows us to access attributes in our code if we use them.
As for me, reflection is most useful when I work with objects that have types that are similar but not equal classes. In this case, I parse the object methods, properties, and attributes, evaluate them, and then use an appropriate decision-making algorithm in the code.
To use Reflection, you should declare:
using System.Reflection;
Reflection Examples in C#
Invoke Value from Method
The section demonstrates how to retrieve a value from an object property using reflection when you are unsure of the property type.
This particular example invokes a value from an enumeration depending on its type. The example needs the method GetEnumByValue
in the same class:
And here is the command to invoke enumeration:
Iterate Object Properties
You can get all the properties of an object using reflection, and then iterate them, check values, and make decisions according to algorithm conditions.
In the example below, we iterate the properties of the object contact, compare the values of each property, and finally generate the property names with different values:
Check if Property is Array
You can check if a property value is an array using the property IsArray
:
Check if Property is Object
The presented example code below verifies if the property value is an object using the property IsClass
. Prior to the verification, the property value is filtered if it is null or array, and these cases are excluded.
TypeDescriptor, Alternative to Reflection
As described previously, Reflection is a generic mechanism that is available to all types, and the information it returns about a type is not extensible, in the sense that it cannot be modified after compilation.
TypeDescriptor, on the other hand, is an extensible inspection mechanism for components: classes that implement the IComponent interface. Unlike reflection, it does not perform method inspections. The TypeDescriptor is dynamically extendable.
The example bellow demonstrates how to convert an object to a dictionary.
Was this helpful?
0 / 0