Reflection in is a beautiful technology. If you do not know anything about an object, you do not have Visual Studio Intellisense support, no problem. Reflection is there.
In this article, we will learn how we can use LINQ effectively with reflection to read objects and its members.
Let's start with a class. I have a class "A" with a property, str.
My task goal here is to read str property at runtime using reflection.
Reflection functionality is defined in the System.Reflection namespace. So, before we can actually use any class, we must import the namespace to your project using the following declaration.
using System.Reflection;
Now, let's create a simple C# console application and define our A class this as discussed above. Also, let's use LINQ to read the class.
In the above code, I wrote a simple LINQ statement to get the type of A and get its properties using the GetProperties() method.
However, we are not done yet. There is still some work left. Now, I am acutally going to add a "where" clause to our LINQ statement and check for proeprty "str".
IEnumerable<PropertyInfo> query = from o in a.GetType().GetProperties()
where o.Name == "str"
select o;
Now I have access to the property and I can just read any details about it. I can get its value. I can learn about its type and so on. The PropertyInfo list gives me all information about a property. I can access it as following:
The following list shows the complete code:
Run the Program.
Works Well.
Lets just put the code in Static method to make it more readable.
Final Code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace AcessProperty
{
class Program
{
static void Main(string[] args)
{
getPropValue("str");
Console.ReadLine();
}
public static void getPropValue(string MethodName)
{
A a = new A();
a.str = "Welcome to Reflection";
IEnumerable<PropertyInfo> query = from o in a.GetType().GetProperties()
where o.Name == MethodName
select o;
foreach (PropertyInfo p in query)
{
Console.WriteLine(p.GetValue(a, null));
}
}
}
public class A
{
public string str { get; set; }
}
}
Summary
In this article, we learned how to use reflection to read a class property and its value. I used LINQ to read the property. In my future articles, I will discuss some more interesting tasks we could perform using Reflection.