Type.getType() can't find the class

2.4k views Asked by At

I have a lot of static methods in a class, I want to get if a certain method is in the class X, and if it is, I want to invoke it. I checked with this:

if (Type.GetType("Homework.Homework.Functions").GetMethod(methodName) == null)
            {
                Console.WriteLine("No such method.\nPress any key to restart the program");
                Console.ReadKey();
                Console.Clear();
                Main();
                return;
            }
            else
                Type.GetType("Homework.Homework.Functions").GetMethod(methodName).Invoke(null, parametersArray); // Invoking the method.

But it gives me a System.NullReferenceException in the line with the if() in it.

The starting of the program:

namespace Homework
{
class Homework
{
    static void Main()
    {

Declaration of the class:

public class Functions
    {

I probably should say that the class Functions is inside the class Homework.

How do I solve this error?

Thanks.

2

There are 2 answers

0
Jon Skeet On

The problem is that nested types are separated with a + rather than a . in the IL name. If you write:

Console.WriteLine(typeof(global::Homework.Homework.Functions));

then you'll see the fully qualified name as far as the CLR is concerned.

So you want:

Type.GetType("Homework.Homework+Functions")

Assuming you really need to get it by name - avoid this sort of thing where possible. Use typeof wherever you know the type at compile-time (and are happy to have a reference if it's in a different assembly).

That will work if you're calling it from within the same assembly. If you're calling Type.GetType from a different assembly, you'll need to qualify the name with the assembly as well.

I'd also strongly encourage you not to name a class the same as its namespace.

0
mrtig On

You need to specify an assembly qualified name to GetType(string). Instantiate your Homework class and look at its

GetType().FullName