How to Get Property Names using Reflection in C#?
How to Get Property Names using Reflection in C#?
In this article, I will show you how you can get the name of all properties using Reflection in C# at runtime.
To get the name of properties of a specific type use Type.GetProperties method. This method returns the array of PropertyInfo object. From this object you can find the name of property through PropertyInfo.Name property.
To get the name of properties of a specific type use Type.GetProperties method. This method returns the array of PropertyInfo object. From this object you can find the name of property through PropertyInfo.Name property.
To get properties information of class. First of all add the following namespace in your cs page.
using System.Reflection;
For example, we have the following class
class MyTestClass
{
public int A { get; set; }
public string B { get; set; }
}
{
public int A { get; set; }
public string B { get; set; }
}
Now write the following code to get the property name of above class
MyTestClass obj = new MyTestClass();
//Get the type instance
Type t = obj.GetType();
//Get all properties on MyTestClass
PropertyInfo[] propinfo = t.GetProperties();
//Get the type instance
Type t = obj.GetType();
//Get all properties on MyTestClass
PropertyInfo[] propinfo = t.GetProperties();
foreach (PropertyInfo prop in propinfo)
{
//Write the name of the property
Console.WriteLine(prop.Name);
}
{
//Write the name of the property
Console.WriteLine(prop.Name);
}
Hope you would have enjoyed this simple article on getting the names of properties of C# class using reflections.