Get Type by Name
Solution 1
Type.GetType
can only find types in mscorlib
or current assembly when you pass namespace qualified name. To make it work you need "AssemblyQualifiedName".
The assembly-qualified name of the type to get. See AssemblyQualifiedName. 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.
Referece Type.GetType
System.ServiceModel.NetNamedPipeBinding
lives in "System.ServiceModel.dll" hence Type.GetType
can't find it.
This will work
Type.GetType(typeof(System.ServiceModel.NetNamedPipeBinding).AssemblyQualifiedName)
Or if you know the assembly already use following code
assemblyOfThatType.GetType(fullName);//This just need namespace.TypeName
Solution 2
If you want use simple name (not AssemblyQualifiedName), and don't worry about ambiguous, you can try something like this:
public static Type ByName(string name)
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Reverse())
{
var tt = assembly.GetType(name);
if (tt != null)
{
return tt;
}
}
return null;
}
Reverse() - for load most recently loaded type (for example after compilation of code from aspx)
Yaugen Vlasau
Updated on June 20, 2022Comments
-
Yaugen Vlasau almost 2 years
In my code I am trying to get a type by name. When I was using a string argument I failed. Then I have tried to do the follwing in the Quick watch window:
Type.GetType(typeof(System.ServiceModel.NetNamedPipeBinding).Name)
returns null. Why? and how to get the desired type by name?
-
clcto over 10 yearsWhats wrong with just
typeof(System.ServiceModel.NetNamedPipeBinding)
-
Yaugen Vlasau over 10 yearsThe question is about how to do it by a type name...
-
-
Yaugen Vlasau over 10 yearsyou are right. thanks! can you give me any ideas about getting to AssemblyQualifiedName from the type name? or how can I get an instnace of NetNamedPipeBinding by name "NetNamedPipeBinding". Initial idea was Activator.CreateInstance(myType); where my type was a correct type
-
Sriram Sakthivel over 10 yearsAtleast do you know which assembly type lives in?
-
Sriram Sakthivel over 10 yearsCheck my update if that helps.. to get assembly instance use typeof(AnyTypeFromServiceModelAssembly).Assembly
-
Yaugen Vlasau over 10 yearsWow! this is a solution for all possible cases :). but in my case assemblyOfThatType.GetType(fullName) was enough!