How to get Property Name of a Class as a String at runtime in C#?
How to get Property Name of a Class as a String at runtime in C#?
Getting property names of class at runtime is the rare situation but it has very simple solution. In this article, I will try to give very basic example of getting property names of class in C# at runtime and storing that property name as a string. Suppose I have a public class say ClassName and this class has property say IntProperty which returns integer type.
public class ClassName
{
public static int IntProperty { get { return 0; } }
}
{
public static int IntProperty { get { return 0; } }
}
Lets say I have to fetch the name of each property as a string at runtime, then I will have to use PropertyInfo and typeof keywords to get the name of properties at runtime. Below is the code c# snippet for this.
foreach (PropertyInfo p in typeof(ClassName).GetProperties())
{
string propertyName = p.Name;
//....
}
{
string propertyName = p.Name;
//....
}
In this case I have taken the example of class which has only one property for making the article simple. But by using foreach loop which I have used you can assign names of properties to list of string at runtime as per your requirement.