user2707101
user2707101

Reputation: 28

C# GetCustomattributes from class name

Is it possible to get the custom attributes from the class name as a string?

something like this (which doesn't work)

Type myType = Type.GetType("MyClass");
MemberInfo info = myType // typeof(myType);
object[] atts = info.GetCustomAttributes(true);

Upvotes: 1

Views: 3313

Answers (2)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

You're almost there. You missed namespace.

 Type myType = Type.GetType("System.String");
 object[] atts = myType.GetCustomAttributes(true);

In your case

Type myType = Type.GetType("YourNameSpace.MyClass");//this should work

Refer Type.GetType for more info

var asnames = Assembly.GetExecutingAssembly().GetReferencedAssemblies();
var asmname = asnames.FirstOrDefault(x => x.Name == assemName);
Assembly.Load(asmname);

Use the above code to preload the assembly(If it exists in your referenced assembly)

Upvotes: 2

SecureTeam Software
SecureTeam Software

Reputation: 141

It looks like you're almost there.

Use object[] atts = Type.GetType("MyNamesapce.MyClass").GetCustomAttributes(true);

Worked flawlessly for me

Perhaps you missed mentioning the namespace?.

Check http://msdn.microsoft.com/en-us/library/system.attribute.getcustomattributes.aspx

Upvotes: 0

Related Questions