4

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.

MKasprzyk
  • 503
  • 5
  • 17
  • Are you locked in on having a list of `string`, or could you have a list of `Type` instead? If you only have `string`s, how do you want to handle the situation where there are more than one type by the same name (in different namespaces)? – Tomas Aschan Jul 11 '16 at 13:54
  • Unfortunately i'm locked. List of classes is from text file, and i need to create appropriate objects. – MKasprzyk Jul 11 '16 at 13:57
  • Be sure to check out this thread as well : [How to get all classes within namespace?](https://stackoverflow.com/questions/949246/how-to-get-all-classes-within-namespace/949285#949285) – Paul Gorbas Sep 25 '17 at 18:49

2 Answers2

5

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.

Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402
2

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.)

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193