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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With