This code:
Type.GetType(\"namespace.a.b.ClassName\")
returns null
.
and I have in the usings:
using nam
I am opening user controls depending on what user controls the user have access to specified in a database. So I used this method to get the TypeName...
Dim strType As String = GetType(Namespace.ClassName).AssemblyQualifiedName.ToString
Dim obj As UserControl = Activator.CreateInstance(Type.GetType(strType))
So now one can use the value returned in strType to create an instance of that object.
Try this method.
public static Type GetType(string typeName)
{
var type = Type.GetType(typeName);
if (type != null) return type;
foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
{
type = a.GetType(typeName);
if (type != null)
return type;
}
return null;
}
Type.GetType("namespace.qualified.TypeName")
only works when the type is found in either mscorlib.dll or the currently executing assembly.
If neither of those things are true, you'll need an assembly-qualified name:
Type.GetType("namespace.qualified.TypeName, Assembly.Name")
When I have only the class name I use this:
Type obj = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).Where(t => String.Equals(t.Name, _viewModelName, StringComparison.Ordinal)).First();
As Type.GetType(String) need the Type.AssemblyQualifiedName you should use Assembly.CreateQualifiedName(String, String).
string typeName = "MyNamespace.MyClass"; // Type.FullName
string assemblyName = "MyAssemblyName"; // MyAssembly.FullName or MyAssembly.GetName().Name
string assemblyQualifiedName = Assembly.CreateQualifiedName(assemblyName , typeName);
Type myClassType = Type.GetType(assemblyQualifiedName);
The Version, Culture and PublicKeyToken are not required for assemblyName
that's why you can use MyAssembly.GetName().Name.
About Type.GetType(String) :
If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.
If the assembly is part of the build of an ASP.NET application, you can use the BuildManager class:
using System.Web.Compilation
...
BuildManager.GetType(typeName, false);