what i want to do is to automatically create some object.
In Java, class can be pass as parameter, for example
Class A{ } Object createObjectBy(class clazz){ // .. do construction work here } when using it, just ---> createObjectBy(A.class)
it is benefit for a lot of things.
so, how can i do similar thing in C#????
Object createObjectBy(Type clazz){ // .. do construction work here Object theObject = Activator.CreateInstance(clazz); return theObject; }
Usage:
createObjectBy(typeof(A));
Or you could simply use Activator.CreateInstance
directly :-)
The ideal way would be to use generics
public static T CreateInstance<T>() where T: new() { // Do some business logic Logger.LogObjectCreation(typeof(T)); // Actualy instanciate the object return new T(); }
A call example would look like
var employee = CreateInstance<Employee>();
If the type of object is unknown at runtime, for example through a plugin system, you need to use the Type
class:
public static object CreateInstance(Type type) { // Do some business logic Logger.LogObjectCreation(type); // Actualy instanciate the object return Activator.CreateInstance(type); }
A call example would look like
var instance = CreateInstance(someType);
Of course, nothing beats instanciating an object than by using the keyword new
. Except maybe not instanciating, but instead reusing an object, like through caching.
If you have to settle for the second method where the type is unknown, there are some alternatives to Activator.CreateInstance
. Although the article recommend using lambda expression, your biggest consideration is:
If you only need to create your object once, just stick with the Activator.CreateInstance method. If you need to create it multiple time in a short time, try the lambda approach. That last approach is similar to a compiled regular expression vs. an on-the-fly regular expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With