I have a base class which needs to process the names of the properties of derived classes (explicit access). To do so, I created a method which takes a lambda expression as input:
private string GetMemberName(Expression<Func<object>> expression)
{
//gets the property name (MemberExpression or UnaryExpression)
//out of scope
return propertyName;
}
This allows me to call the method like so:
derived.GetMemberName(() => derived.MyPropertyInt);
derived.GetMemberName(() => derived.MyPropertyStr);
The problem is that object is not restrictive at all. I can also call:
derived.GetMemberName(() => "something"); //does not "return" anything but compiles (out of scope)
derived.GetMemberName(() => anotherClass.RandomMember); //not derived from "base"
How can I restrict the GetMemberName method so that it can only accept as input the members of the classes which derive from my base class? Setting GetMemberName(Expression<Func<MyBaseClass>> expression) restricts access to an entire class. Setting GetMemberName(Expression<Func<MyBaseClass, object>> expression) restricts access to the current instance but still allows "random" objects to be passed.
EDIT:
The comment for derived.GetMemberName(() => "something"); was in the context of returning the property name, not the "value" of the lambda expression. The GetPropertyName method does not return anything, due to the fact that I'm only analyzing MemberExpression or UnaryExpression.