Search code examples
c#stringtypestypeof

I have a C# class which i have to get the type of... but i only have the name(single name) as a string


i have a class named Hacker and i have a class Spy in witch i have to do a method that takes the name(single name) of Hacker class but ass a string "Hacker" do some work and return it as a string and im suppose to get the job done by this code in my main method:

        Spy spy = new Spy();
        string result = spy.AnalyzeAccessModifiers("Hacker");
        Console.WriteLine(result);

In my AnalyzeAccessModifiers method I tried:

public string AnalyzeAccessModifiers(string className)
    {
     // i need to get some job done with:
     Type type = Type.GetType(classname);//but it need the fully qualified name for that.
     // so i tried:
     Type type = typeof(className); // but it does not work with string...
    }

is there any way this to be done when i only have the name as a string ...the only way i can think off is by using the actual class name as a type not as a string but that is not in the description of my task...


Solution

  • Sadly Type.GetType(string) is quite finicky about the details it requires before it will give you the result. If the type you're looking for is in current executing assembly (or mscorlib/System.Private.CoreLib) then a fully specified name (including namespace) will get the result. If it's in a different assembly then you need to specify the assembly name.

    Type type = null;
    
    // Fails
    type = Type.GetType("String");
    
    // Succeeds from core library
    type = Type.GetType("System.String");
    
    // Fails (loading from a different assembly)
    type = Type.GetType("System.Text.Json.JsonSerializer");
    
    // Succeeds (.NET 6.0)
    type = Type.GetType("System.Text.Json.JsonSerializer, System.Text.Json");
    

    Which is all well and good until you're trying to find a type that you have exactly one piece of information about: the class name. Without namespace and assembly name you're stuck with enumerating every type until you find what you're looking for...

    static Type? TypeFromName(string name) =>
        // All loaded assemblies
        AppDomain.CurrentDomain.GetAssemblies()
        // All types in loaded assemblies
        .SelectMany(asm => asm.GetTypes())
        // Return first match
        .FirstOrDefault(type => type.Name == name);
    

    Simple, yes. Fast? Not even remotely. But you only need to do the search once and cache the results for later use.