Get Type by Name

14,368

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)

Share:
14,368
Yaugen Vlasau
Author by

Yaugen Vlasau

Updated on June 20, 2022

Comments

  • Yaugen Vlasau
    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
      clcto over 10 years
      Whats wrong with just typeof(System.ServiceModel.NetNamedPipeBinding)
    • Yaugen Vlasau
      Yaugen Vlasau over 10 years
      The question is about how to do it by a type name...
  • Yaugen Vlasau
    Yaugen Vlasau over 10 years
    you 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
    Sriram Sakthivel over 10 years
    Atleast do you know which assembly type lives in?
  • Sriram Sakthivel
    Sriram Sakthivel over 10 years
    Check my update if that helps.. to get assembly instance use typeof(AnyTypeFromServiceModelAssembly).Assembly
  • Yaugen Vlasau
    Yaugen Vlasau over 10 years
    Wow! this is a solution for all possible cases :). but in my case assemblyOfThatType.GetType(fullName) was enough!