In several places, I noticed that expression trees were passed as arguments to methods that let you check the names of objects. For example, Caliburn Micro has the following method signature in its PropertyChangedBase class:
public virtual void NotifyOfPropertyChange<TProperty>(Expression<Func<TProperty>> property);
I have a custom attribute that I would like to have the same type of property name compiler check in the constructor so that I can type:
[MyCustomAttribute(() => PropertyName)]
Instead:
[MyCustomAttribute("PropertyName")]
Using constructor definition in strings:
public MyCustomAttribute(params Expression<Func<object>>[] properties)
However, due to the restriction on the parameters of the attribute, which is constant expressions, this seems impossible.
Can someone recommend a different approach when I can get the compiler to check the property names in the parameters of my attribute and not leave this potential error that uses only strings?
Edit: thanks Marc answer, I have implemented this for now:
#if DEBUG foreach (var propertyInfo in GetType().GetProperties().Where(propertyInfo => Attribute.IsDefined(propertyInfo, typeof (MyCustomAttribute)))) { foreach (var propertyName in propertyInfo.GetAttributes<MyCustomAttribute>(true) .SelectMany(attribute => attribute.PropertyNames)) Debug.Assert( GetType().GetProperty(propertyName) != null, "Property not found", "Property {0} declared on attributed property {1} was not found on type {2}.", propertyName, propertyInfo.Name, GetType().Name ); }