<p>One may not always know the <code>Type</code> of an object at compile-time, but may need to create an instance of the <code>Type</code>.  </p>

<p>How do you get a new object instance from a <code>Type</code>?</p>

[{'answer_id': 755, 'author': 'Karl Seguin', 'author_id': 34, 'author_profile': 'https://Stackoverflow.com/users/34', 'pm_score': 11, 'selected': True, 'text': '<p>The <code>Activator</code> class within the root <code>System</code> namespace is pretty powerful.</p>\n\n<p>There are a lot of overloads for passing parameters to the constructor and such. Check out the documentation at: </p>\n\n<blockquote>\n  <p><a href="http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx</a></p>\n</blockquote>\n\n<p>or (new path)</p>\n\n<blockquote>\n  <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance" rel="noreferrer">https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance</a></p>\n</blockquote>\n\n<p>Here are some simple examples:</p>\n\n<pre><code>ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);\n\nObjectType instance = (ObjectType)Activator.CreateInstance("MyAssembly","MyNamespace.ObjectType");\n</code></pre>\n'}, {'answer_id': 26031, 'author': 'Tom Mayfield', 'author_id': 2314, 'author_profile': 'https://Stackoverflow.com/users/2314', 'pm_score': 4, 'selected': False, 'text': '<p>If this is for something that will be called a lot in an application instance, it\'s a lot faster to compile and cache dynamic code instead of using the activator or <code>ConstructorInfo.Invoke()</code>.  Two easy options for dynamic compilation are compiled <a href="http://rogeralsing.com/2008/02/28/linq-expressions-creating-objects/" rel="noreferrer">Linq Expressions</a> or some simple <a href="http://web.archive.org/web/20140926050502/http://www.ozcandegirmenci.com/post/2008/02/Create-object-instances-Faster-than-Reflection.aspx" rel="noreferrer"><code>IL</code> opcodes and <code>DynamicMethod</code></a>.  Either way, the difference is huge when you start getting into tight loops or multiple calls.</p>\n'}, {'answer_id': 26033, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 7, 'selected': False, 'text': '<p>The answer was already given:</p>\n<blockquote>\n<pre><code>ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);\n</code></pre>\n</blockquote>\n<p>However, the <code>Activator</code> class has a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance?view=net-7.0#system-activator-createinstance-1" rel="nofollow noreferrer">generic variant for the parameterless constructor</a> that makes this slightly more readable by making the cast unnecessary and not needing to pass the runtime type of the object:</p>\n<pre><code>ObjectType instance = Activator.CreateInstance&lt;ObjectType&gt;();\n</code></pre>\n'}, {'answer_id': 3503517, 'author': 'Brady Moritz', 'author_id': 177242, 'author_profile': 'https://Stackoverflow.com/users/177242', 'pm_score': 4, 'selected': False, 'text': "<p>Wouldn't the generic <code>T t = new T();</code> work? </p>\n"}, {'answer_id': 12343731, 'author': 'vikram nayak', 'author_id': 196857, 'author_profile': 'https://Stackoverflow.com/users/196857', 'pm_score': 3, 'selected': False, 'text': '<pre><code>public AbstractType New\n{\n    get\n    {\n        return (AbstractType) Activator.CreateInstance(GetType());\n    }\n}\n</code></pre>\n'}, {'answer_id': 17797389, 'author': 'BSharp', 'author_id': 2237957, 'author_profile': 'https://Stackoverflow.com/users/2237957', 'pm_score': 4, 'selected': False, 'text': '<p>If you want to use the default constructor then the solution using <code>System.Activator</code> presented earlier is probably the most convenient. However, if the type lacks a default constructor or you have to use a non-default one, then an option is to use reflection or <code>System.ComponentModel.TypeDescriptor</code>. In case of reflection, it is enough to know just the type name (with its namespace).</p>\n\n<p>Example using reflection:</p>\n\n<pre><code>ObjectType instance = \n    (ObjectType)System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(\n        typeName: objectType.FulName, // string including namespace of the type\n        ignoreCase: false,\n        bindingAttr: BindingFlags.Default,\n        binder: null,  // use default binder\n        args: new object[] { args, to, constructor },\n        culture: null, // use CultureInfo from current thread\n        activationAttributes: null\n    );\n</code></pre>\n\n<p>Example using <code>TypeDescriptor</code>:</p>\n\n<pre><code>ObjectType instance = \n    (ObjectType)System.ComponentModel.TypeDescriptor.CreateInstance(\n        provider: null, // use standard type description provider, which uses reflection\n        objectType: objectType,\n        argTypes: new Type[] { types, of, args },\n        args: new object[] { args, to, constructor }\n    );\n</code></pre>\n'}, {'answer_id': 26708746, 'author': 'Sarath Subramanian', 'author_id': 3312636, 'author_profile': 'https://Stackoverflow.com/users/3312636', 'pm_score': 5, 'selected': False, 'text': '<p>Its pretty simple. Assume that your classname is <code>Car</code> and the namespace is <code>Vehicles</code>, then pass the parameter as <code>Vehicles.Car</code> which returns object of type <code>Car</code>. Like this you can create any instance of any class dynamically.</p>\n\n<pre><code>public object GetInstance(string strNamesapace)\n{         \n     Type t = Type.GetType(strNamesapace); \n     return  Activator.CreateInstance(t);         \n}\n</code></pre>\n\n<p>If your <a href="https://msdn.microsoft.com/en-us/library/dfb3cx8s%28v=vs.71%29.aspx" rel="noreferrer">Fully Qualified Name</a>(ie, <code>Vehicles.Car</code> in this case) is in another assembly, the <code>Type.GetType</code> will be null. In such cases, you have loop through all assemblies and find the <code>Type</code>. For that you can use the below code</p>\n\n<pre><code>public object GetInstance(string strFullyQualifiedName)\n{\n     Type type = Type.GetType(strFullyQualifiedName);\n     if (type != null)\n         return Activator.CreateInstance(type);\n     foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())\n     {\n         type = asm.GetType(strFullyQualifiedName);\n         if (type != null)\n             return Activator.CreateInstance(type);\n     }\n     return null;\n }\n</code></pre>\n\n<p>And you can get the instance by calling the above method.</p>\n\n<pre><code>object objClassInstance = GetInstance("Vehicles.Car");\n</code></pre>\n'}, {'answer_id': 29239907, 'author': 'Darrel Lee', 'author_id': 307968, 'author_profile': 'https://Stackoverflow.com/users/307968', 'pm_score': 2, 'selected': False, 'text': '<p>I can across this question because I was looking to implement a simple CloneObject method for arbitrary class (with a default constructor)</p>\n\n<p>With generic method you can require that the type implements New().</p>\n\n<pre><code>Public Function CloneObject(Of T As New)(ByVal src As T) As T\n    Dim result As T = Nothing\n    Dim cloneable = TryCast(src, ICloneable)\n    If cloneable IsNot Nothing Then\n        result = cloneable.Clone()\n    Else\n        result = New T\n        CopySimpleProperties(src, result, Nothing, "clone")\n    End If\n    Return result\nEnd Function\n</code></pre>\n\n<p>With non-generic assume the type has a default constructor and catch\nan exception if it doesn\'t.</p>\n\n<pre><code>Public Function CloneObject(ByVal src As Object) As Object\n    Dim result As Object = Nothing\n    Dim cloneable As ICloneable\n    Try\n        cloneable = TryCast(src, ICloneable)\n        If cloneable IsNot Nothing Then\n            result = cloneable.Clone()\n        Else\n            result = Activator.CreateInstance(src.GetType())\n            CopySimpleProperties(src, result, Nothing, "clone")\n        End If\n    Catch ex As Exception\n        Trace.WriteLine("!!! CloneObject(): " &amp; ex.Message)\n    End Try\n    Return result\nEnd Function\n</code></pre>\n'}, {'answer_id': 29972767, 'author': 'Serj-Tm', 'author_id': 1034136, 'author_profile': 'https://Stackoverflow.com/users/1034136', 'pm_score': 7, 'selected': False, 'text': '<p>Compiled expression is best way! (for performance to repeatedly create instance in runtime).</p>\n\n<pre><code>static readonly Func&lt;X&gt; YCreator = Expression.Lambda&lt;Func&lt;X&gt;&gt;(\n   Expression.New(typeof(Y).GetConstructor(Type.EmptyTypes))\n ).Compile();\n\nX x = YCreator();\n</code></pre>\n\n<p>Statistics (2012):</p>\n\n<pre><code>    Iterations: 5000000\n    00:00:00.8481762, Activator.CreateInstance(string, string)\n    00:00:00.8416930, Activator.CreateInstance(type)\n    00:00:06.6236752, ConstructorInfo.Invoke\n    00:00:00.1776255, Compiled expression\n    00:00:00.0462197, new\n</code></pre>\n\n<p>Statistics (2015, .net 4.5, x64):</p>\n\n<pre><code>    Iterations: 5000000\n    00:00:00.2659981, Activator.CreateInstance(string, string)\n    00:00:00.2603770, Activator.CreateInstance(type)\n    00:00:00.7478936, ConstructorInfo.Invoke\n    00:00:00.0700757, Compiled expression\n    00:00:00.0286710, new\n</code></pre>\n\n<p>Statistics (2015, .net 4.5, x86):</p>\n\n<pre><code>    Iterations: 5000000\n    00:00:00.3541501, Activator.CreateInstance(string, string)\n    00:00:00.3686861, Activator.CreateInstance(type)\n    00:00:00.9492354, ConstructorInfo.Invoke\n    00:00:00.0719072, Compiled expression\n    00:00:00.0229387, new\n</code></pre>\n\n<p>Statistics (2017, LINQPad 5.22.02/x64/.NET 4.6):</p>\n\n<pre><code>    Iterations: 5000000\n    No args\n    00:00:00.3897563, Activator.CreateInstance(string assemblyName, string typeName)\n    00:00:00.3500748, Activator.CreateInstance(Type type)\n    00:00:01.0100714, ConstructorInfo.Invoke\n    00:00:00.1375767, Compiled expression\n    00:00:00.1337920, Compiled expression (type)\n    00:00:00.0593664, new\n    Single arg\n    00:00:03.9300630, Activator.CreateInstance(Type type)\n    00:00:01.3881770, ConstructorInfo.Invoke\n    00:00:00.1425534, Compiled expression\n    00:00:00.0717409, new\n</code></pre>\n\n<p>Statistics (2019, x64/.NET 4.8):</p>\n\n<pre><code>Iterations: 5000000\nNo args\n00:00:00.3287835, Activator.CreateInstance(string assemblyName, string typeName)\n00:00:00.3122015, Activator.CreateInstance(Type type)\n00:00:00.8035712, ConstructorInfo.Invoke\n00:00:00.0692854, Compiled expression\n00:00:00.0662223, Compiled expression (type)\n00:00:00.0337862, new\nSingle arg\n00:00:03.8081959, Activator.CreateInstance(Type type)\n00:00:01.2507642, ConstructorInfo.Invoke\n00:00:00.0671756, Compiled expression\n00:00:00.0301489, new\n</code></pre>\n\n<p>Statistics (2019, x64/.NET Core 3.0):</p>\n\n<pre><code>Iterations: 5000000\nNo args\n00:00:00.3226895, Activator.CreateInstance(string assemblyName, string typeName)\n00:00:00.2786803, Activator.CreateInstance(Type type)\n00:00:00.6183554, ConstructorInfo.Invoke\n00:00:00.0483217, Compiled expression\n00:00:00.0485119, Compiled expression (type)\n00:00:00.0434534, new\nSingle arg\n00:00:03.4389401, Activator.CreateInstance(Type type)\n00:00:01.0803609, ConstructorInfo.Invoke\n00:00:00.0554756, Compiled expression\n00:00:00.0462232, new\n</code></pre>\n\n<p>Full code:</p>\n\n<pre><code>static X CreateY_New()\n{\n    return new Y();\n}\n\nstatic X CreateY_New_Arg(int z)\n{\n    return new Y(z);\n}\n\nstatic X CreateY_CreateInstance()\n{\n    return (X)Activator.CreateInstance(typeof(Y));\n}\n\nstatic X CreateY_CreateInstance_String()\n{\n    return (X)Activator.CreateInstance("Program", "Y").Unwrap();\n}\n\nstatic X CreateY_CreateInstance_Arg(int z)\n{\n    return (X)Activator.CreateInstance(typeof(Y), new object[] { z, });\n}\n\nprivate static readonly System.Reflection.ConstructorInfo YConstructor =\n    typeof(Y).GetConstructor(Type.EmptyTypes);\nprivate static readonly object[] Empty = new object[] { };\nstatic X CreateY_Invoke()\n{\n    return (X)YConstructor.Invoke(Empty);\n}\n\nprivate static readonly System.Reflection.ConstructorInfo YConstructor_Arg =\n    typeof(Y).GetConstructor(new[] { typeof(int), });\nstatic X CreateY_Invoke_Arg(int z)\n{\n    return (X)YConstructor_Arg.Invoke(new object[] { z, });\n}\n\nprivate static readonly Func&lt;X&gt; YCreator = Expression.Lambda&lt;Func&lt;X&gt;&gt;(\n   Expression.New(typeof(Y).GetConstructor(Type.EmptyTypes))\n).Compile();\nstatic X CreateY_CompiledExpression()\n{\n    return YCreator();\n}\n\nprivate static readonly Func&lt;X&gt; YCreator_Type = Expression.Lambda&lt;Func&lt;X&gt;&gt;(\n   Expression.New(typeof(Y))\n).Compile();\nstatic X CreateY_CompiledExpression_Type()\n{\n    return YCreator_Type();\n}\n\nprivate static readonly ParameterExpression YCreator_Arg_Param = Expression.Parameter(typeof(int), "z");\nprivate static readonly Func&lt;int, X&gt; YCreator_Arg = Expression.Lambda&lt;Func&lt;int, X&gt;&gt;(\n   Expression.New(typeof(Y).GetConstructor(new[] { typeof(int), }), new[] { YCreator_Arg_Param, }),\n   YCreator_Arg_Param\n).Compile();\nstatic X CreateY_CompiledExpression_Arg(int z)\n{\n    return YCreator_Arg(z);\n}\n\nstatic void Main(string[] args)\n{\n    const int iterations = 5000000;\n\n    Console.WriteLine("Iterations: {0}", iterations);\n\n    Console.WriteLine("No args");\n    foreach (var creatorInfo in new[]\n    {\n        new {Name = "Activator.CreateInstance(string assemblyName, string typeName)", Creator = (Func&lt;X&gt;)CreateY_CreateInstance},\n        new {Name = "Activator.CreateInstance(Type type)", Creator = (Func&lt;X&gt;)CreateY_CreateInstance},\n        new {Name = "ConstructorInfo.Invoke", Creator = (Func&lt;X&gt;)CreateY_Invoke},\n        new {Name = "Compiled expression", Creator = (Func&lt;X&gt;)CreateY_CompiledExpression},\n        new {Name = "Compiled expression (type)", Creator = (Func&lt;X&gt;)CreateY_CompiledExpression_Type},\n        new {Name = "new", Creator = (Func&lt;X&gt;)CreateY_New},\n    })\n    {\n        var creator = creatorInfo.Creator;\n\n        var sum = 0;\n        for (var i = 0; i &lt; 1000; i++)\n            sum += creator().Z;\n\n        var stopwatch = new Stopwatch();\n        stopwatch.Start();\n        for (var i = 0; i &lt; iterations; ++i)\n        {\n            var x = creator();\n            sum += x.Z;\n        }\n        stopwatch.Stop();\n        Console.WriteLine("{0}, {1}", stopwatch.Elapsed, creatorInfo.Name);\n    }\n\n    Console.WriteLine("Single arg");\n    foreach (var creatorInfo in new[]\n    {\n        new {Name = "Activator.CreateInstance(Type type)", Creator = (Func&lt;int, X&gt;)CreateY_CreateInstance_Arg},\n        new {Name = "ConstructorInfo.Invoke", Creator = (Func&lt;int, X&gt;)CreateY_Invoke_Arg},\n        new {Name = "Compiled expression", Creator = (Func&lt;int, X&gt;)CreateY_CompiledExpression_Arg},\n        new {Name = "new", Creator = (Func&lt;int, X&gt;)CreateY_New_Arg},\n    })\n    {\n        var creator = creatorInfo.Creator;\n\n        var sum = 0;\n        for (var i = 0; i &lt; 1000; i++)\n            sum += creator(i).Z;\n\n        var stopwatch = new Stopwatch();\n        stopwatch.Start();\n        for (var i = 0; i &lt; iterations; ++i)\n        {\n            var x = creator(i);\n            sum += x.Z;\n        }\n        stopwatch.Stop();\n        Console.WriteLine("{0}, {1}", stopwatch.Elapsed, creatorInfo.Name);\n    }\n}\n\npublic class X\n{\n  public X() { }\n  public X(int z) { this.Z = z; }\n  public int Z;\n}\n\npublic class Y : X\n{\n    public Y() {}\n    public Y(int z) : base(z) {}\n}\n</code></pre>\n'}, {'answer_id': 31138841, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>Without use of Reflection:</p>\n\n<pre><code>private T Create&lt;T&gt;() where T : class, new()\n{\n    return new T();\n}\n</code></pre>\n'}, {'answer_id': 31143718, 'author': 'Thulani Chivandikwa', 'author_id': 611628, 'author_profile': 'https://Stackoverflow.com/users/611628', 'pm_score': 4, 'selected': False, 'text': '<p>Given this problem the Activator will work when there is a parameterless ctor. If this is a constraint consider using </p>\n\n<pre><code>System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject()\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/192/']