I’m wondering if following code is “safe”. By “safe” I mean that I don’t depend on some specific compiler version or undocumented feature.
I want to get string with property / field name, but I want to declare it using strong typing (I want the compiler to check if specific field / property exists).
My method looks like this:
string GetPropertyName<T>(Expression<Func<T, object>> expression)
{
if (expression.Body is UnaryExpression)
{
var operand = ((UnaryExpression)expression.Body).Operand.ToString();
return operand.Substring(operand.IndexOf(".") + 1);
}
else if (expression.Body is MemberExpression)
{
return ((MemberExpression)expression.Body).Member.Name;
}
else
{
throw new NotImplementedException();
}
}
And here is how I want to use it:
class Foo
{
public string A { get; set; }
public Bar B { get; set; }
}
class Bar
{
public int C { get; set; }
public Baz D { get; set; }
}
class Baz
{
public int E { get; set; }
}
GetPropertyName<Foo>(x => x.A)
GetPropertyName<Foo>(x => x.B)
GetPropertyName<Foo>(x => x.B.C)
GetPropertyName<Foo>(foo => foo.B.D.E)
Thanks in advance for help.
I’m not sure that the output of the
ToStringmethod is guaranteed in any way. The documentation just says that it “returns a textual representation of theExpression“.(I suspect that the output is unlikely to change across different platforms/versions, but I’d be a bit reluctant to rely on it when your aim is to use strong typing, compile-time checks etc.)
Here’s my method that does something similar without using
ToString: