Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    }
}
like image 616
Rosstified Avatar asked Dec 17 '12 22:12

Rosstified


People also ask

What is method and attribute?

A method is a function defined in the class. An attribute is an instance variable defined in the class.

What are attributes used for in C#?

Attributes are used in C# to convey declarative information or metadata about various code elements such as methods, assemblies, properties, types, etc. Attributes are added to the code by using a declarative tag that is placed using square brackets ([ ]) on top of the required code element.

Does C# have annotations?

An annotation on a program element (commonly a class, method, or field) is a piece of meta-data added to that program element which can be used to embellish that element with extra code. In Java this is called an annotation, in C# this is called an attribute.


1 Answers

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.

like image 52
Fabio Avatar answered Sep 25 '22 15:09

Fabio