10

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)
    {

    }
}
Jared Harley
  • 8,219
  • 4
  • 39
  • 48
Rosstified
  • 4,047
  • 2
  • 25
  • 33
  • _I can fall back to use strings, but prefer to use compiler time to verify the types are correct._ => C# 6 introduced the nameof expression, giving you back a string but with compiler/refactoring. support.https://msdn.microsoft.com/nl-be/library/dn986596.aspx – janv8000 Jan 25 '17 at 13:52

2 Answers2

2

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.

Community
  • 1
  • 1
Fabio
  • 3,020
  • 4
  • 39
  • 62
  • Cheers, that would work, but I think i'll just go for passing in the type (as Type) and method name as string. I'm only processing the attributes at startup, so can process into MethodInfo then via reflection. – Rosstified Dec 18 '12 at 01:00
0

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.

Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39