Search code examples
c#referenceprivatemember

Getting a direct reference to a private member name instead of using string


I'm using a library that requires I pass names of my private members, presumably so it can do some reflection internally:

m_MaterialsProp = serializedObject.FindProperty("m_Materials");

As I refactor and move things around it becomes a nightmare to ensure these strings remain correct.

Is it possible for me to get a safe reference to the private member, and pass the member name to the function instead?


Solution

  • public string GetMemberName<T>(Expression<Func<T>> memberExpression)
        {
            MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
            return expressionBody.Member.Name;
        }