This question already has an answer here:
I have a property in Myclass
:
public class MyClass{
public string FirstName {get;set;}
}
How can I get the PropertyInfo
(using GetProperty("FirstName")
) without a string?
Today I use this:
PropertyInfo propertyTitleNews = typeof(MyClass).GetProperty("FirstName");
Is there a way for use like this:
PropertyInfo propertyTitleNews = typeof(MyClass).GetProperty(MyClass.FirstName);
?
You could do that
With this helper :
Another possibility, beside Ivan Danilov's answer, is to provide an extension method:
And then use it like this:
The drawback is that you need an instance, but an advantage is that you don't need to supply generic arguments.
See here. The idea is to use Expression Trees.
And then use it like:
A bit cleaner solution would be if one would not required to specify so much generic parameters. And it is possible via moving
MyClass
generic param to util class:Then usage will be cleaner: