8protons
8protons

Reputation: 3959

Why do I have to specify the namespace in the parameter for assembly.GetType()?

Take the below example:

var assembly = Assembly.Load("ProjA.Primates");
var myType = assembly.GetType("ProjA.Primates.Bonobo");

If I do not specify the "ProjA.Primates." substring, an exception is thrown.

Why can't it successfully find the Bonobo type in the loaded assembly?

Upvotes: 3

Views: 140

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726609

Namespace name is part of the type's full name. For example, full name of List<T> is System.Collections.Generic.List<T>

Using full names everywhere would be inconvenient, so C# lets you skip namespace the part by adding a using directive at the top of your source. However, this is only a compiler trick that adds the namespace to the list of places to look for type resolution.

You can use LINQ to look up a class by its name (as opposed to its full name) as follows:

var myType = assembly.GetTypes().SingleOrDefault(t => t.Name == "Bonobo");

Note: Your approach is stricter, in the sense that changing the namespace would result in an error. The approach above, on the other hand, is less predictable because you may or may not want to pick a class from a different namespace. In addition, it's going to fail if there are multiple classes in the same assembly with the same short name and different namespaces.

Upvotes: 3

Related Questions