Thursday 18 April 2013

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

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();

foreach (PropertyInfo prop in propinfo)
  //Write the name of the property

Hope you would have enjoyed this simple article on getting the names of properties of C# class using reflections.

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.