C # how to get the name (in string) of a class property?

public class TimeZone { public int Id { get; set; } public string DisplayName{ get; set; } } 

In some other class, I:

  var gmtList = new SelectList( repository.GetSystemTimeZones(), "Id", "DisplayName"); 

Note. System.Web.Mvc.SelectList

I do not like to write the name of the property with "Id" and "DisplayName". Later, the property name may change and the compiler will not detect this error. C # how to get property name in string?

UPDATE 1

With the help of Christian Heiter, I can use:

 var tz = new TimeZone(); var gmtList = new SelectList( repository.GetSystemTimeZones(), NameOf(() => tz.Id), NameOf(() => tz.TranslatedName)); 

OR

 var gmtList = new SelectList( repository.GetSystemTimeZones(), NameOf(() => new TimeZone().Id), NameOf(() => new TimeZone().TranslatedName)); 

If someone has another idea, without the need to create a new object. Feel free to share it :) thanks.

+2
source share
5 answers

You can create a utility method to extract the property name from the expression tree, for example:

 string NameOf<T>(Expression<Func<T>> expr) { return ((MemberExpression) expr.Body).Member.Name; } 

Then you can call it like this:

 var gmtList = new SelectList(repository.GetSystemTimeZones(), NameOf(() => tz.Id), NameOf(() => tz.DisplayName)); 

Please note that any instance of the class will work, since you are not reading the value of the property, only the name.

+13
source

(These are not btw parameters, they are properties.)

Well, one option is to use delegates. For instance:

 public class SelectList<T> { public SelectList(IEnumerable<T> source, Func<T, string> idProjection, Func<T, string> displayProjection) { ... } } 

Then:

 var gmtList = new SelectList<TimeZone>(repository.GetSystemTimeZones(), tz => tz.Id, tz => tz.DisplayName); 
0
source

var name = (string) typeof(TimeZone).GetProperty("DisplayName").GetValue(0);

0
source
 string id=typeof(TimeZone).GetProperties()[0].Name; string displayName=typeof(TimeZone).GetProperties()[1].Name; var gmtList = new SelectList( repository.GetSystemTimeZones(), id, displayName); 

this will work if the order in which the id is declared and the display name does not change. or you can think of defining an attribute for a property to distinguish between id and displayname.

0
source

Starting with C # 6.0, now you can use

 var gmtList = new SelectList( repository.GetSystemTimeZones(), nameof(TimeZone.Id), nameof(TimeZone.DisplayName)); 
0
source

Source: https://habr.com/ru/post/915273/


All Articles