Create New Instance From Type in C#

This tutorial will discuss the methods of creating a new instance of a given data type at runtime in C#.

Create a New Instance From Type With the Activator Class in C

If we want to create a new instance of a data type at runtime and do not know the data type, we can use the Activator class and the Type class to achieve this goal. The Activator class provides methods for creating instances of objects from types in C#. The Activator.CreateInstance() method is used to create an instance of a specified type with the constructor that best suits the specified type in C#. The Type class represents a data type in C#. We can use the Type class to determine the unknown data type in this scenario. The following code example shows us how we can create a new instance of a data type at runtime without knowing the data type using the Activator class and the Type class in C#.

using System;

namespace new_object_from_type
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 123;
            Type t = i.GetType();
            Object n = Activator.CreateInstance(t);
            n = 15;
            Console.WriteLine(n);
        }
    }
}

Output:

15

In the above code, we created an instance of the type int32 at the runtime without specifying the data type with the Activator.CreateInstance() method in C#. At first, we determined the type of the variable i with the i.GetType() method in C#. Then, we created an instance of that type with the Activator.CreateInstance() method. The Activator.CreateInstance() method automatically finds the best constructor for the data type and creates an instance with it. We then initialized the new instance n with the value 15 and printed it.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.