Shachaf.Gortler
Shachaf.Gortler

Reputation: 5745

Load a Type from Assembly using simple class name

I try to load a type by reflection

I successfully found the assembly containing the type :

 var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(t => t.GetTypes().Any(g => g.Name == "MyClass"));

but when I try to load the type from the assembly like so :

Type t = assembly.GetType("MyClass");

Then t is null, I don't want to load the type using the full qualifying name, just the class name.

Upvotes: 1

Views: 382

Answers (1)

user2160375
user2160375

Reputation:

If you don't want to use full qualifying name you need to search via LINQ and manually handle the case, where more than one class is found:

var types = assembly.GetTypes().Where(type => type.Name == "MyClass");
var firstType = types.FirstOrDefault();

Remember/lesson: there could be more than one class in assembly with the same name (classes that have different namespaces).

Upvotes: 8

Related Questions