views:

60

answers:

3

I need to be able to read the value of my attribute from within my Method, how can I do it?

[MyAttribute("Hello World")]
public int MyMethod()
{
    //Need to read the MyAttribute attribute and get its value
}
A: 

Look into reflection.

http://msdn.microsoft.com/en-us/library/z919e8tw(v=VS.80).aspx

NickLarsen
+3  A: 
[MyAttribute("Hello World")]
public int MyMethod()
{
var myAttribute = GetType().GetMethod("MyMethod").GetCustomAttributes(true).OfType<MyAttribute>().FirstOrDefault();
}
Nagg
Brings a whole new meaning to the expression "self reflection"...
Oded
+4  A: 

You need to call the GetCustomAttributes function on a MethodBase object.
The simplest way to get the MethodBase object is to call MethodBase.GetCurrentMethod. (Note that you should add [MethodImpl(MethodImplOptions.NoInlining)])

For example:

MethodBase method = MethodBase.GetCurrentMethod();
MyAttribute attr = (MyAttribute)method.GetCustomAttributes(typeof(MyAttribute), true)[0] ;
string value = attr.Value;    //Assumes that MyAttribute has a property called Value

You can also get the MethodBase manually, like this: (This will be faster)

MethodBase method = typeof(MyClass).GetMethod("MyMethod");
SLaks