1

How to get the PropertyName of a class?

For example, How can I get the PropertyName "StudentName" of a Student class instance.

public class Student
{
    public string StudentName{get;set;}
}


Student student = new Student();

//I want to get the PropertyName "StudentName"
student.StudentName.GetName(); 
Mike108
  • 2,089
  • 7
  • 34
  • 45
  • 2
    I don't understand, if you already know the property then by definition you already know the name of the property? – Dean Harding Apr 21 '10 at 05:57
  • 1
    Is there any reason not to directly type in "StudentName" as a string? Maybe, you can get better answers if you try to explain what you are trying to achieve. – Amry Apr 21 '10 at 05:59
  • It is used for other class, so I do not want to hard-type the string. – Mike108 Apr 21 '10 at 06:40
  • Duplicate of: http://stackoverflow.com/questions/301809/workarounds-for-nameof-operator-in-c-typesafe-databinding/301957#301957, http://stackoverflow.com/questions/869610/c-resolving-a-parameter-name-at-runtime, http://stackoverflow.com/questions/301809/workarounds-for-nameof-operator-in-c-typesafe-databinding – vgru Apr 21 '10 at 07:36

2 Answers2

2

To get the actual name of the property, just from having access to the class, you can use the following:

Type studentType = typeof(Student);
PropertyInfo[] AllStudentProperties = studentType.GetProperties();

If you know the name you're looking for and just need access to the property itself, use:

Type studentType = typeof(Student);
PropertyInfo StudentProperties = studentType.GetProperty("StudentName");

Once you have the PropertyInfo, simply use PropertyInfo.Name, which will give the string representation.

If after this you wan't the value, you're going to have to have an instantiated class to get the value. Other than this, if you use a static property, you can pull the value without instantiating it.

Kyle Rosendo
  • 25,001
  • 7
  • 80
  • 118
2

Updated answer:

C# now has a nameof operator, so you should use that.

You can use it on the instance or the Student type itself.

Example:

nameof(student.StudentName); // returns "StudentName"
nameof(Student.StudentName); // returns "StudentName"

Original answer (written before nameof existed):

You can use the following static method:

static string GetName<T>(T item) where T : class
{
    var properties = typeof(T).GetProperties();
    return properties[0].Name;
}

Use like so:

string name = GetName(new { student.StudentName });

See this question for details.

Matthew King
  • 5,114
  • 4
  • 36
  • 50