Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find namespace of class by its name using reflection in .net core?

I have a list of string with only classes names. I need to create instances of them using Activator, but all of them can be in diffrent namespaces. Classes can be move into another namespace in the future so i can't hardcode it.

like image 254
MKasprzyk Avatar asked Mar 11 '23 17:03

MKasprzyk


2 Answers

If you know that you'll never have multiple types with the same name residing in the different namespaces, you can just iterate over all types in the assembly and filter on type name. For example, this works:

var typenames = new[] { "String", "Object", "Int32" };

var types =  typeof(object).GetTypeInfo().Assembly
    .GetTypes()
    .Where(type => typenames.Contains(type.Name))
    .ToArray(); // A Type[] containing System.String, System.Object and System.Int32

This won't necessarily break if you have multiple types with the same name, but you'll get all of them in the list.

like image 180
Tomas Aschan Avatar answered Apr 07 '23 06:04

Tomas Aschan


You can get all the types of an assembly and find the one with the name in question.

var type = assembly.GetTypes().FirstOrDefault(x => x.Name == name);

Note: the name may not be unique. In such a case, you don't have a chance to find the correct type, unless you can have some guess about the namespace 8e.g. list of possible namespaces, "blacklist" of namespaces etc.)

like image 23
Stefan Steinegger Avatar answered Apr 07 '23 06:04

Stefan Steinegger