1

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);
user2707101
  • 28
  • 1
  • 5

2 Answers2

2

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)

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • Type myType = Type.GetType("YourNameSpace.MyClass"); returns null for me. Is there a way to get this for referenced assemblies - possibly that have not been used, so may not be loaded (if .NET does lazy load?) – user2707101 Sep 12 '13 at 14:40
  • @user2707101 Am afraid, It is possible but why do you need to pre load the assembly? – Sriram Sakthivel Sep 12 '13 at 15:03
  • This works: String strFile = assemName + ".dll"; Byte[] bytes = System.IO.File.ReadAllBytes(dllPath + strFile); Assembly assem = Assembly.Load(bytes); Type typeDefinition = assem.GetType(assemName + ".Entity." + entityName); But there must be an easier way to get the Type? – user2707101 Sep 12 '13 at 15:23
0

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

  • Thanks this works with "System.String" but not with "Mynamespace.myclass" - which is in a separate dll, but referenced and has a using statement so should be available. Maybe I have to do something with GetAssembly. – user2707101 Sep 12 '13 at 14:33