System.Type.GetType vs. System.Web.Compilation.BuildManager.GetType

I was writing some code that will create an object to the interface based on it's name (using System.Activator.CreateInstance). To do this, I need the name of the Class to create and from that I need to return the System.Type. Now... here's the catch. System.Type.GetType will only search through the .Net Framework classes and the executing assembly. This afternoon, I hit a snag because I needed to use the System.Type.GetType on a class that was in my App_Code directory. An runtime, ASP.NET compiles the App_Code directory into assemblies with dynamic names which means I can't pass System.Type.GetType the assembly name (it will return a null Type, even if you specific the namespace/assembly properly). The way around this?... use System.Web.Compilation.BuildManager.GetType. This class is smart enough to look through the dynamic assemblies also that ASP.NET creates when the site builds. Below is example of the BuildManager.GetType usage:

' GetType from a class in the ASP.NET App_Code directory.
Dim reportType As Type = System.Web.Compilation.BuildManager.GetType(li.Value, False)
Dim report As IReportWriter

     ' Creates an instance of our report, and passes in the constructor values
     report = System.Activator.CreateInstance(reportType, conn, reportTable)
Catch ex As Exception
     ' Eat error for this example.
End Try

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.