Get property-name of a general abstract class
Given the following implementation of a generic abstract class:
public abstract class BaseRequest<TGeneric> : BaseResponse where TRequest : IRequestFromResponse
{
public TGeneric Request { get; set; }
}
Is it possible to get the name of a property Request
without having an inherited instance?
I need it Request
as a string "Request"
to avoid using hardcoded strings. Any ideas how to do this via reflection?
source to share
Since C # 6, you can use the operator nameof
:
string propertyName = nameof(BaseRequest<ISomeInterface>.Request);
The generic type parameter used for BaseRequest<T>
is irrelevant (as long as it satisfies the type constraints) since you are not instantiating any object from that type.
For C # 5 and older, you can use Cameron MacFarland's answer to get property information from lambda expressions. Below is a simplified adaptation (no error checking):
public static string GetPropertyName<TSource, TProperty>(
Expression<Func<TSource, TProperty>> propertyLambda)
{
var member = (MemberExpression)propertyLambda.Body;
return member.Member.Name;
}
Then you can use it like this:
string propertyName = GetPropertyName((BaseRequest<ISomeInterface> r) => r.Request);
// or //
string propertyName = GetPropertyName<BaseRequest<ISomeInterface>, ISomeInterface>(r => r.Request);
source to share
Can you elaborate on what you are trying to achieve? It looks like you are making requests to the web API, for what purpose do you want to specify the property name and in what context?
This will give you the names of all properties in the object type:
var properties = typeof(MyClass).GetProperties(BindingFlags.Public | BindingFlags.Static).Select(p => p.Name);
source to share