Please I don't know what I am doing wrong, when I run this code, I get an exception: Value cannot be null.... When I run it in debug mode, I see that "calculatorInstance" variable is null. Please help me out.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace ReflectionWithLateBinding
{
public class Program
{
static void Main()
{
//load the current executing assembly
Assembly executingAssembly = Assembly.GetExecutingAssembly();
//load and instantiate the class dynamically at runtime - "Calculator class"
Type calculatorType = executingAssembly.GetType("ReflectionWithLateBinding.Calculator");
//Create an instance of the type --"Calculator class"
object calculatorInstance = Activator.CreateInstance(calculatorType);
//Get the info of the method to be executed in the class
MethodInfo sumArrayMethod = calculatorType.GetMethod("SumNumbers");
object[] arrayParams = new object[2];
arrayParams[0] = 5;
arrayParams[1] = 8;
int sum;
sum = (int)sumArrayMethod.Invoke(calculatorInstance, arrayParams);
Console.WriteLine("Sum = {0}", sum);
Console.ReadLine();
}
public class Calculator
{
public int SumNumbers(int input1, int input2)
{
return input1 + input2;
}
}
}
}
I'm pretty sure it's actually the GetType
method which is returning null
- because there's no type with the fully-qualified name ReflectionWithLateBinding.Calculator
. Your Calculator
class is nested within your Program
class.
It's the call to Activator.CreateInstance
which is throwing an exception, therefore the assignment to calculatorInstance
is never made - it's not that the variable has a value of null
, but rather that its declaration statement (which includes the initializer) never completes.
Options (don't do both!):
Program
class (i.e. so it's declared directly in the namespace)GetType
call to executingAssembly.GetType("ReflectionWithLateBinding.Program+Calculator")
See more on this question at Stackoverflow