views:

67

answers:

4

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

+1  A: 

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))]
A: 

No, you can't. Attributes only accept certain compile-time constants.

John Saunders
+1  A: 

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

Paja
That reference is for C# 1.1, btw - not C# 4 (although it's still valid info, unfortunately)
Reed Copsey
+1  A: 

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

Reed Copsey