Hi,
I think the title says it all. I want a static helper method to remove magic strings. Of course, I could pack the property method inside the TestContainer, which would remove the need to provide the TestContainer as argument. This is done nicely here.
But I would like to have the helper method in one static class, in case I later decide to optimize my code and remove the method. I managed to get it down to this, but its a little bit ugly (having to provide the string type, looks not very nice).
Any "expression god" knowing a better way. Keep in mind, the static class should be kept universal and not know anything about the TestContainer (otherwise it would be as easy as the link provided)
internal class PropertyNameResolving
{
internal class TestContainer
{
public string LastName { get; set; }
}
internal static class BindingHelper
{
public static string PropertyName<TObject, TValue>(Expression<Func<TObject, TValue>> propertySelector)
{
var memberExpression = propertySelector.Body as MemberExpression;
if (memberExpression != null) return memberExpression.Member.Name;
else
throw new Exception("Something went wrong");
}
}
internal static void Test()
{
var t = new TestContainer {LastName = "Hans"};
Console.WriteLine(BindingHelper.PropertyName<TestContainer, string>(x => x.LastName));
Console.ReadLine();
}
}
Btw, the output is "LastName" and can be used to set bindings.
And one more question, can I remove the NULL check safely?