Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a string representation of a property in C# at run-time

I have seen the reverse of this question quite a few times, but have not seen how to do what I would like.

Suppose I have the following code:

var myNewData = from t in someOtherData
            select new
            { 
                fieldName = t.Whatever,
                fieldName2 = t.SomeOtherWhatever
            };

If I wish to data bind to this class, my column definition would have to include hard-coded strings like "fieldName" and "fieldName2".

Is there any way to call reflection or something else so that I can do something equivelent to the code below (I know the code below is not valid, but am looking for a valid solution).

string columnName = GetPropertyName(myNewData[0].fieldName);

My goal is that if the variable name changes on the anonymous class, a compile-time error would come up until all references were fixed, unlike the current data binding which relies on strings that are not checked until runtime.

Any help would be appreciated.

like image 874
gwerner Avatar asked Jan 22 '23 05:01

gwerner


1 Answers

string columnName = GetPropertyName(() => myNewData[0].fieldName);

// ...

public static string GetPropertyName<T>(Expression<Func<T>> expr)
{
    // error checking etc removed for brevity

    MemberExpression body = (MemberExpression)expr.Body;
    return body.Member.Name;
}
like image 113
LukeH Avatar answered Feb 16 '23 00:02

LukeH