Pages

Saturday 13 April 2013

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; } }
}

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;
    //....
}

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.

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.