Search code examples
.netreflectionsystem.reflection

Best way to get a Type object from a string in .NET


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

Issues to consider:

  • The type may be in a different assembly.
  • The type's assembly may not be loaded yet.

This is my attempt, but it doesn't address the second issue

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

Solution

  • you might need to call 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);
            }
        }
    }