Can you use a lambda expressions as an argument to an attribute? The motivation I am thinking of would be to eliminate reliance on magic strings
Cheers, Berryl
Can you use a lambda expressions as an argument to an attribute? The motivation I am thinking of would be to eliminate reliance on magic strings
Cheers, Berryl
I wish but it does not seem as though you can.
You can encapsulate what you want in a type and reference the type, though.
public interface Accessor
{
object GetValue(object source);
}
public class ExpressionDrivenAccessor<T, U> : Accessor
{
private readonly Func<T, U> getIt;
protected ExpressionDrivenAccessor(Expression<Func<T, U>> expression)
{
getIt = expression.Compile();
}
public object GetValue(object source)
{
return getIt((T)source);
}
}
public class SomeAccessor : ExpressionDrivenAccessor<X, Y>
{
public SomeAccessor() : base(t => t.SomeProperty) { }
}
[MyAttribute(typeof(SomeAccessor))]
No, you can't. Attributes only accept certain compile-time constants.
http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx
Attribute parameters are restricted to constant values of the following types:
Simple types
(bool, byte, char, short, int, long, float, and double)
string
System.Type
enums
object
(The argument to an attribute parameter of type object must be a constant value of one of the above types.)
One-dimensional arrays of any of the above types
No. There is a compiler error specification that handles this:
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type