Create Instance Of a Type - CSharp System.Reflection

CSharp examples for System.Reflection:Type

Description

Create Instance Of a Type

Demo Code


using System.Reflection;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//from   w ww.  j  av  a2 s . c  o  m

public class Main{
        public static object CreateInstanceOf(this Type instanceType, bool noConstructor = false)
      {
         try
         {
            if (instanceType == typeof(string))
               return "";
            else if (typeof(Array).IsAssignableFrom(instanceType) && instanceType.GetArrayRank() == 1)
               return Array.CreateInstance(instanceType.GetElementType(), 0);
            else if (noConstructor)
               return System.Runtime.Serialization.FormatterServices.GetUninitializedObject(instanceType);
            else
               return Activator.CreateInstance(instanceType, true);
         }
         catch (Exception)
         {
            return null;
         }
      }
}

Related Tutorials