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

I have a list of strings with class names. I need to instantiate them using Activator, but they can all be in different namespaces. Classes may move to another namespace in the future, so I cannot hardcode it.

+3
reflection c # asp.net-core
source share
2 answers

If you know that you will never have multiple types with the same name that are in different namespaces, you can simply iterate over all types in the assembly and filter the 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 will not necessarily break if you have several types with the same name, but you will get all of them in the list.

+4
source share

You can get all types of assembly and find one who has the corresponding name.

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

Note: the name may not be unique. In this case, you cannot find the correct type, unless you can guess about the 8e.g namespace. list of possible namespaces, blacklist of namespaces, etc.)

+1
source share

All Articles