Passing Property Names the "compiler-safe" Way
2 min read
2 min read
A common bad practice which I often find when browsing through code is to see people directly hard-code strings in their source code. I've also proposed some refactorings in some of my previous posts. Today I'd like to blog about a similar issue which targets the issue of object property referencing within code.
I guess most of us already had the case where you give a property of your entity likeSomeHelper.Validate(entityObject, "somePropertyName", value);This "strange" assignment because SetProperty takes objects in a generic way and validates the specified property. Note, this is not real-world code, so don't be scared :) , but it may arise in similar ways throughout your code-base.
SomeHelper.Validate(entityObject, "someOtherPropertyName", value);
MyLogger.LogProblem("SomePropertyName", "Some message from a resource file");
public static void LogProblem<T>(Expression<Func<T>> propertyExpression, string message)This can then be used very nicely by rewriting the logging instruction I mentioned before like this
{
string propertyName = GetPropertyName(propertyExpression);
if (propertyName == null)
throw new NullReferenceException("The name of the property couldn't be retrieved!");
LogEntry logEntry = new LogEntry()
{
Fieldname = propertyName,
MessageDescription = String.Format(message, propertyName)
};
logEntries.Add(logEntry);
}
public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
MemberExpression body = (MemberExpression)expression.Body;
return body.Member.Name;
}
MyLogger.LogProblem(() => myObjInstance.SomePropertyName, "Some message from a resource file");Voilá, you have a compile-time, fully intellisense supported logging method now. The only thing I don't really like is the somehow strange-looking declaration of the property name by having to use
() =>
...