Search code examples
c#methodsreflectionsystem.reflectionmethodinfo

How to properly use GetMethod from inside a namespace?


For example, we have the following code, given by Microsoft

public class MagicClass
{
    private int magicBaseValue;

    public MagicClass()
    {
        magicBaseValue = 9;
    }

    public int ItsMagic(int preMagic)
    {
        return preMagic * magicBaseValue;
    }
}

public class TestMethodInfo
{
    public static void Main()
    {
        // Get the constructor and create an instance of MagicClass

        Type magicType = Type.GetType("MagicClass");
        ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes);
        object magicClassObject = magicConstructor.Invoke(new object[]{});

        // Get the ItsMagic method and invoke with a parameter value of 100

        MethodInfo magicMethod = magicType.GetMethod("ItsMagic");
        object magicValue = magicMethod.Invoke(magicClassObject, new object[]{100});

        Console.WriteLine("MethodInfo.Invoke() Example\n");
        Console.WriteLine("MagicClass.ItsMagic() returned: {0}", magicValue);
    }
}

// The example program gives the following output:
//
// MethodInfo.Invoke() Example
//
// MagicClass.ItsMagic() returned: 900

MethodInfo magicMethod = magicType.GetMethod("ItsMagic"); is where the program would break, if we had enclosed this whole snippet of code in any namespace of our choosing.

The exception it throws is the following: System.NullReferenceException: 'Object reference not set to an instance of an object.'


Solution

  • If you read the docs:

    typeName

    The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

    So you have to at least specify the namespace when MagicClass is enclosed in a namespace:

    Type magicType = Type.GetType("YourNameSpace.MagicClass");
    

    otherwise it will return null.