Tuesday, April 16, 2013

How To- Get Property Names using Reflection in C#

In this post, I will show you how you can get the name of all properties using Reflection in C#.

In my previous posts, I explained Hard drive information using C#, Create Directory/Folder using C#, Check Internet Connection using C#, SQL Server Database BackUp using C#, Partial Methods, Contextual Keyword, C# Static Methods and some other articles related to C#, ASP.Net and SQL Server.


Get Property Names-

To get the name of properties of a specific type use Type.GetProper­ties 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


Property Names

I hope this will be helpful for you. I would like to have any feedback from you. Your valuable feedback, question, or comments about this article are always welcome.

No comments:

Post a Comment

If You Enjoyed This Post Please Take 5 Seconds To Share It.

^ Scroll to Top hgpromo