I need to be able to read the value of my attribute from within my Method, how can I do that?
[MyAttribute("Hello World")]
public void MyMethod()
{
// Need to read the MyAttribute attribute and get its value
}
I need to be able to read the value of my attribute from within my Method, how can I do that?
[MyAttribute("Hello World")]
public void MyMethod()
{
// Need to read the MyAttribute attribute and get its value
}
You need to call the
GetCustomAttributes
function on aMethodBase
object.The simplest way to get the
MethodBase
object is to callMethodBase.GetCurrentMethod
. (Note that you should add[MethodImpl(MethodImplOptions.NoInlining)]
)For example:
You can also get the
MethodBase
manually, like this: (This will be faster)If you store the default attribute value into a property (
Name
in my example) on construction, then you can use a static Attribute helper method:Usage:
My solution is based on that the default value is set upon the attribute construction, like this:
The available answers are mostly outdated.
This is the current best practice:
This requires no casting and is pretty safe to use.
You can also use
.GetCustomAttributes<T>
to get all attributes of one type.In case you are implementing the setup like @Mikael Engver mentioned above, and allow multiple usage. Here is what you can do to get the list of all the attribute values.