Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Type by Name

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?

like image 999
Yaugen Vlasau Avatar asked Nov 27 '25 02:11

Yaugen Vlasau


1 Answers

If you want to use simple name (not an AssemblyQualifiedName), and don't worry about ambiguity, 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;
    }

Calling Reverse() is needed for giving priority to most recently loaded types (for example after compilation of code from aspx)

like image 98
Vladimir Avatar answered Nov 29 '25 15:11

Vladimir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!