System.Reflection Library in C#

Ömer Faruk LALE
5 min readJul 21, 2022

In C# programming language, we can retrieve the elements(properties, constructers, methods etc.) of a class by object, reference and name of the class. But sometimes, we need to be able to retrieve or inspect these elements at the run time by just the type of it. At that point, the System.Reflection library of the C# is going to help us about it and in this article we are going to take a look what is the reflection, how can we use it and in which cases should we use it.

The Reflection is used to retrieve metadata on types at runtime. Actually, if you know the elements of the related type, the reflection operations are not really matter. But if you do not know the elements of the type (=generic classes or generic methods) and also if we need to retrieve members of this class, Reflection is the best way to get them.

Firstly, we will get the name, namespace, properties, constructors, methods and method’s attributes of the class by functions which are offered by the Reflection library. To do that, let’s create a class which is called Customer;

public class Customer
{
// Properties
public int Id { get; set; }
// Attributes
[StringLength(30)] // → It comes from the System.DataAnnotations
public string FirstName { get; set; }
// Attributes
[Required] // → It comes from the System.DataAnnotations
public string LastName { get; set; }
public string Address { get; set; }
private string Age { get; set; }
private string Email { get; set; }
// Constructers
public Customer() { }
public Customer(string _FirstName)
{
FirstName = _FirstName;
}
private Customer(string _FirstName, string _LastName)
{
FirstName = _FirstName;
LastName = _LastName;
}
// Methods
public bool Validate(Customer customer)
{
return true;
}
private string GetFullName(string firstName, string lastName)
{
return firstName + " " + lastName;
}
// Attributes
[Obsolete("Do not use this method. Use 'NewMethodForAttribute' method.")]
public void OldMethodForAttribute() { }
public void NewMethodForAttribute() { }
}

In this class, these private and public elements were deliberately set to be able to see that, we can not retrieve the private elements by using below reflection functions.

After creating our entity class, let’s create the main class(=Program.cs) to use reflection functions and see behaviors of them in it.

using System.ComponentModel.DataAnnotations;
using System.Reflection;
Type type = typeof(Customer);
Console.WriteLine("Class name: " + type.Name);
Console.WriteLine("Namespace of the class: " + type.Namespace);
Console.WriteLine("----------------------------------");
PropertyInfo[] propertyInfo = type.GetProperties();
Console.WriteLine("The List of Properties of the Customer Class are:");
foreach (PropertyInfo item in propertyInfo)
{
foreach (var attribute in item.GetCustomAttributes().ToList())
{
Console.WriteLine("Attribute → [" + attribute.GetType().Name + "]");
}
Console.WriteLine(item.Name + "\n");
}
Console.WriteLine("----------------------------------");
ConstructorInfo[] constructorInfo = type.GetConstructors();
Console.WriteLine("The Customer Class Contains the Following Constructors:");
foreach (ConstructorInfo item in constructorInfo)
{
Console.WriteLine(item);
}
Console.WriteLine("----------------------------------");
MethodInfo[] methodInfo = type.GetMethods();
Console.WriteLine("The Methods of the Customer Class are:");
foreach (MethodInfo item in methodInfo)
{
foreach (var attribute in item.GetCustomAttributes().ToList())
{
Console.WriteLine("Attribute → [" + attribute.GetType().Name + "]");
}
Console.WriteLine(item.Name + "\n");
}

The output of the above functions is;

As you can see at the output image, we can retrieve Class name and namespace of the class by typeof, list of the properties by GetProperties function which returns a list type of PropertyInfo, list of constructors by GetConstructors function which returns a list type of ConstructorInfo, list of methods by GetMethods function which returns a list type of MethodInfo and all attributes of any element which has at least an attribute by GetCustomAttributes() method which returns list type of Attribute.

There are two important points at the output image.

The first one is; there are just public elements of the class in the lists. Because Reflection functions can retrieve only public elements.

And the second one is; in the method list, there are some methods which are not exist in our Customer class(=ToString, Equals, GetHashCode, GetType). Why the class has these methods? The reason is; all classes are derives the Object class by default and Object class has these methods in the .Net. Because of that reason, the Customer class has also these methods.

Now, let’s use these retrieved methods in the main(=Program.cs) again.

using System.Reflection;Customer customer = new Customer();
customer.GetType().GetProperties().ToList().ForEach(p =>
{
if (p.Name == "FirstName")
{
p.SetValue(customer, "Ömer Faruk");
}
else if (p.Name == "LastName")
{
p.SetValue(customer, "LALE");
}
else if (p.Name == "Address")
{
p.SetValue(customer, "Turkey");
}
});
Console.WriteLine(customer.FirstName + " " + customer.LastName + " - " + customer.Address);

We created a new instance of the Customer object, and then we get the properties of it. For each property, we checked their names manually by if-else statement. And we set the value as we want, if the property name is same with the one that we gave manually. Also the output of this code block is;

Output of the Above Code Block

I think, you are asking this question to yourself right now.

“Why do we use reflection if we know what are the properties of the class that we are using?”

In my opinion, this point is the place where you are going to understand exactly what the reflection is used for.

Okay. Up to this time, we have used reflection functions for a class whose properties have already known by us. But, what if we have to work on a class that we have no idea about its elements(=properties, constructors, methods, attributes etc). The last sentence is same with “What if we have to work on a class which is generic or has generic extension methods?”.

Let’s think about it on an example;

It is an generic class and it has generic extension method in it. This operation makes oldObject equal to newObject and returns the updated oldObject. Also the types of them can be everything as long as they are same type, renewable and class (because of the generic constraint of the class). Because of that reason, there is no chance to know their properties. So, we have to use reflection for them. By using this facility, we can set the same properties to each other without knowing which type they have.

Also, even if we know the type of the objects that we want to make equal to each other, we might need to add new property(ies) for our type in the future of the software life cycle. In this situation, you have to refactor your code for your new elements (like properties) at the places that you have not used reflection like comment lines of the below code;

Author : Ömer Faruk LALE

To Reach Me : https://www.linkedin.com/in/omerlaleee/

--

--