The best way to get a Type object from a string in .NET.

What is the best way to convert a string to a Type object in .NET?

Questions to consider:

  • The type may be in a different assembly.
  • The type node is not yet loaded.

This is my attempt, but it does not address the second problem.

Public Function FindType(ByVal name As String) As Type Dim base As Type base = Reflection.Assembly.GetEntryAssembly.GetType(name, False, True) If base IsNot Nothing Then Return base base = Reflection.Assembly.GetExecutingAssembly.GetType(name, False, True) If base IsNot Nothing Then Return base For Each assembly As Reflection.Assembly In _ AppDomain.CurrentDomain.GetAssemblies base = assembly.GetType(name, False, True) If base IsNot Nothing Then Return base Next Return Nothing End Function 
+6
reflection system.reflection
source share
2 answers

you may need to call the GetReferencedAssemblies () method for the second.

 namespace reflectme { using System; public class hello { public hello() { Console.WriteLine("hello"); Console.ReadLine(); } static void Main(string[] args) { Type t = System.Reflection.Assembly.GetExecutingAssembly().GetType("reflectme.hello"); t.GetConstructor(System.Type.EmptyTypes).Invoke(null); } } } 
+3
source share

You can use Type.GetType (string) for this . The type name must be qualified, but the method will load the assembly as needed. Assembly qualification is optional if the type is in mscorlid or the assembly that makes the GetType call.

+9
source share

All Articles