Saturday 9 August 2014

Create generic type object by using Activator class

This post aims to show how to create an object from a generic class using the activator class.
Given the class :
public class MyObject
{
        public string Name { get; set; }

}
We can instantiate a new MyObject object by :
var newObject =   (MyObject)Activator.CreateInstance(typeof(MyObject));

What happens if the class looks like :

  public class DataObject<T>
    {
        public DataObject(string name)
        {
            Name = name;
        }
        public string Name { get; set; }
        public List<T> ContenList { get; set; }
    } 
 We can achieve this goal with :

 var dataObjectBody = (DataObject<string>)Activator.CreateInstance(typeof(DataObject<>).MakeGenericType(typeof(string)),"Foody");
 The MakeGenericType tells that we want to use the generic T as a string type.
The "Foody" value is used for the constructor name parameter when the Activator.CreateInstance creates the object at runtime.

In the case where the class uses a multi generic type like:
 public class DataObject1<T,TU>
    {
        public DataObject1(string name)
        {
            Name = name;
        }
        public string Name { get; set; }
        public List<T> ContenListT { get; set; }
        public List<TU> ContenListU { get; set; }
    } 
The same method is being used, we need to do small changes on the arguments

 var obj1 =
                (DataObject1<string, string>)
                    Activator.CreateInstance(typeof (DataObject1<,>).MakeGenericType(typeof (string), typeof (string)),
                        "Foody");


No comments:

Post a Comment