Rosstified
Rosstified

Reputation: 4087

Attribute using method name

I'm thinking you can't but is there a way to reference a method as a parameter on an attribute? I.e. something like below? I can fall back to use strings, but prefer to use compiler time to verify the types are correct.

[LinkToAction(Something)]
public void SomethingElse()
{

}

public static void Something()
{

}

public class LinkToActionAttribute : Attribute
{
    public LinkToActionAttribute(MethodInfo info)
    {

    }
}

Upvotes: 10

Views: 2315

Answers (2)

Tony Hopkinson
Tony Hopkinson

Reputation: 20330

Not directly no. You could pass it as a string and then use reflection to generate a MethodInfo, or better still, mark the methods with LinkedFrom and LinkedTo attributes.

It's not efficient though, validating it would be a bit of work as well, which sort of makes you wonder if attributes are the correct solution.

Upvotes: 0

Fabio
Fabio

Reputation: 3120

Sorry, but you can't. Just these can be passed as arguments for attributes:

  • One of the following types: bool, byte, char, double, float, int, long, short, string.
  • The type object.
  • The type System.Type.
  • An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility.
  • Single-dimensional arrays of the above types.

This question is similar to yours: Is it possible to have a delegate as attribute parameter?. There, a workaround is available which can be useful to you.

Upvotes: 2

Related Questions