TOC

The community is working on translating this tutorial into Turkish, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Reflection:

Instantiating a class

So far, we have worked with .NET types or objects already instantiated. But with Reflection, we can actually do the instantiation at runtime as well, knowing the name of the class we wish to instantiate. There are several ways of doing it, but I prefer getting a reference to the constructor that I wish to use, invoke it, and then use the returned value as my instance. Here's an example of doing just that. Code first, then I will explain it all:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ReflectionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Type testType = typeof(TestClass);
            ConstructorInfo ctor = testType.GetConstructor(System.Type.EmptyTypes);
            if(ctor != null)
            {
                object instance = ctor.Invoke(null);
                MethodInfo methodInfo = testType.GetMethod("TestMethod");
                Console.WriteLine(methodInfo.Invoke(instance, new object[] { 10 }));
            }
            Console.ReadKey();
        }
    }

    public class TestClass
    {
        private int testValue = 42;

        public int TestMethod(int numberToAdd)
        {
            return this.testValue + numberToAdd;
        }
    }
}

I have defined a simple class for testing this, called TestClass. It simply contains a private field and a public method. The method returns the value of the private property, with the value of the parameter added to it. Now, what we want is to create a new instance of this TestClass, call the TestMethod and output the result to the console.

In this example, we have the luxury of being able to use the typeof() directly on the TestClass, but at some point, you may have to do it solely by using the name of the desired class. In that case, you can get a reference to it through the assembly where it is declared, as demonstrated in the chapter about Type.

So, with a Type reference to the class, we ask for the default constructor by using the GetConstructor() method, passing System.Type.EmptyTypes as a parameter. In case we wanted a specific constructor, we would have to provide an array of Type's, each defining which parameter the constructor we were looking for, would take.

Once we have a reference to the constructor, we simply call the Invoke() method to create a new instance of the TestClass class. We pass null as the parameter to Invoke(), since we're not looking to specify any parameters. We use the GetMethod(), along with the name of the method we want, to get the TestMethod() function, and then we once again use the magic of the Invoke() method to call this function. This time we need to specify a parameter, in the form of an array of objects. We do that on-the-fly, specifying the number 10 as the only parameter we need, and we then output the result of the method invocation. All of this through the magic of Reflection!


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!