MKasprzyk
MKasprzyk

Reputation: 499

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.

Upvotes: 4

Views: 5453

Answers (2)

Tomas Aschan
Tomas Aschan

Reputation: 60604

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.

Upvotes: 5

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

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

Upvotes: 2

Related Questions