With generics you can
var object = default(T); But when all you have is a Type instance I could only
constructor = type.GetConstructor(Type.EmptyTypes); var parameters = new object[0]; var obj = constructor.Invoke(parameters); or even
var obj = type.GetConstructor(Type.EmptyTypes).Invoke(new object[0]); Isn't there a shorter way, like the generics version?
To create a new instance of an object, we use the "new" keyword. This keyword creates a new instance of an object, which we can then assign to a variable, or invoke methods. For example, to create a new StringBuffer object, we would use the new keyword in the following way.
Instantiating a Class The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object. The new operator returns a reference to the object it created.
Yes, you can use copy. deepcopy . so just c2 = copy. deepcopy(c) then vars(c2) == {'a': 11, 'r': 2} and vars(c) == {'a': 11, 'r': 2} but the traceback your are reporting wouldn't be produced by the class definition you gave...
The closest available is Activator.CreateInstance:
object o = Activator.CreateInstance(type); ... but of course this relies on there being a public parameterless constructor. (Other overloads allow you to specify constructor arguments.)
I've used an explicitly typed variable here to make it clear that we really don't have a variable of the type itself... you can't write:
Type t = typeof(MemoryStream); // Won't compile MemoryStream ms = Activator.CreateInstance(t); for example. The compile-time type of the return value of CreateInstance is always object.
Note that default(T) won't create an instance of a reference type - it gives the default value for the type, which is a null reference for reference types. Compare that with CreateInstance which would actually create a new object.
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