One may not always know the Type
of an object at compile-time, but may need to create an instance of the Type
. How do you get a new object instance from a Type
?
original title: "c# - How to create a new object instance from a Type"
One may not always know the Type
of an object at compile-time, but may need to create an instance of the Type
. How do you get a new object instance from a Type
?
コンパイル時に常にオブジェクトのタイプを知っているとは限らないかもしれませんが、タイプのインスタンスを作成する必要があるかもしれません。タイプから新しいオブジェクトインスタンスを取得するにはどうすればよいですか?
これは翻訳後の要約です。完全な翻訳を表示する必要がある場合は、「翻訳」アイコンをクリックしてください。
The
Activator
class within the rootSystem
namespace is pretty powerful.There are a lot of overloads for passing parameters to the constructor and such. Check out the documentation at:
or (new path)
Here are some simple examples:
The
Activator
class has a generic variant that makes this a bit easier:Compiled expression is best way! (for performance to repeatedly create instance in runtime).
Statistics (2012):
Statistics (2015, .net 4.5, x64):
Statistics (2015, .net 4.5, x86):
Statistics (2017, LINQPad 5.22.02/x64/.NET 4.6):
Statistics (2019, x64/.NET 4.8):
Statistics (2019, x64/.NET Core 3.0):
Full code:
One implementation of this problem is to attempt to call the parameter-less constructor of the Type:
Here is the same approach, contained in a generic method:
Its pretty simple. Assume that your classname is
Car
and the namespace isVehicles
, then pass the parameter asVehicles.Car
which returns object of typeCar
. Like this you can create any instance of any class dynamically.If your Fully Qualified Name(ie,
Vehicles.Car
in this case) is in another assembly, theType.GetType
will be null. In such cases, you have loop through all assemblies and find theType
. For that you can use the below codeAnd you can get the instance by calling the above method.
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
ConstructorInfo.Invoke()
. Two easy options for dynamic compilation are compiled Linq Expressions or some simpleIL
opcodes andDynamicMethod
. Either way, the difference is huge when you start getting into tight loops or multiple calls.If you want to use the default constructor then the solution using
System.Activator
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 orSystem.ComponentModel.TypeDescriptor
. In case of reflection, it is enough to know just the type name (with its namespace).Example using reflection:
Example using
TypeDescriptor
:Without use of Reflection:
Wouldn't the generic
T t = new T();
work?Given this problem the Activator will work when there is a parameterless ctor. If this is a constraint consider using
I can across this question because I was looking to implement a simple CloneObject method for arbitrary class (with a default constructor)
With generic method you can require that the type implements New().
With non-generic assume the type has a default constructor and catch an exception if it doesn't.