0

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

SpiritBob
  • 2,355
  • 3
  • 24
  • 62
  • https://stackoverflow.com/questions/779091/what-does-object-reference-not-set-to-an-instance-of-an-object-mean – Prasad Telkikar Mar 28 '19 at 12:44
  • If you copy the above could it would work flawlessly, but if you add a namespace to it - it throws the exception. How do we address that? – SpiritBob Mar 28 '19 at 12:48
  • try changing to ".MagicClass" – Matt.G Mar 28 '19 at 12:49
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Trevor Mar 28 '19 at 12:54

2 Answers2

2

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.

Community
  • 1
  • 1
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • I tried that and it throws the same error at ```object magicValue = magicMethod.Invoke(magicClassObject, new object[] { 100 });``` – SpiritBob Mar 28 '19 at 12:58
0

Get the namespace dynamically if it's in the same namespace.

        string ns = typeof(TestMethodInfo).Namespace;
        Type magicType = Type.GetType(ns + ".MagicClass");
Kinimod
  • 166
  • 1
  • 15