4

I am trying to use Cecil to inspect the attributes associated with a given method. It seems to find it, but I cannot get its name using the following code:

AssemblyDefinition assembly = AssemblyFactory.GetAssembly(pathBin);
assembly.MainModule.Types[0].Methods[1].CustomAttributes[0].ToString()

I know this must be the attribute I've set my function to, because when I remove it from the dll, the second line of code will turn out to null. What I'd like to do is be able to get the attribute's name. Currently the second line of code will return just a "Mono.Cecil.CustomAttribute". I'd guess there should be a way of getting an attribute's name(class type) name, right?

Thanks!

devoured elysium
  • 101,373
  • 131
  • 340
  • 557

2 Answers2

7

I had trouble with this when writing MoMA as well. Here is the code it uses:

AssemblyDefinition assembly = AssemblyFactory.GetAssembly(pathBin);
assembly.MainModule.Types[0].Methods[1].CustomAttributes[0].Constructor.DeclaringType.ToString()
jpobst
  • 9,982
  • 1
  • 29
  • 33
  • Funny. That was what I was using now too. – devoured elysium Aug 06 '09 at 16:03
  • 3
    I got that from the author of Cecil, so I think that's the only way. – jpobst Aug 06 '09 at 16:24
  • I am not able to find "AssemblyFactory" class anywhere. I have found all other classes but not this. It seems that this class is not present in mono.cecil dll. Is it present in some other namespace? Can anyone please help me. – samar Nov 11 '11 at 05:50
  • 1
    The new version of Cecil (0.9.4) has a different API. The equivalent to load an assembly is AssemblyDefinition.ReadAssembly (). – jpobst Nov 11 '11 at 15:40
-3

A CustomAttribute is an instance of a System.Attribute derived Type, so ToString() will do whatever the author decided.

If you want to know about attribute types you should ask for their type:

typeInfo.GetCustomAttributes(false)[0].GetType().ToString() ;

I haven't seen this property CustomAttributes you are using, so I rather used the method MemberInfo.GetCustomAttributes(bool) which I always use.

Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66