No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor. If you try to invoke constructors explicitly elsewhere, a compile time error will be generated.
NO. You can't invoke a constructor without creating an object.
To call one constructor from another within the same class (for the same object instance), C# uses a colon followed by the this keyword, followed by the parameter list on the callee constructor's declaration. In this case, the constructor that takes all three parameters calls the constructor that takes two parameters.
Yes, it is possible to call special member functions explicitly by the programmer.
I know that you can directly invoke the static constructor of a type and I know that you can create an instance of an object without calling the constructor, but is there a way to run the constructor of a type (.ctor
) on an already existing instance?
I'm looking for something like:
public static void Reinitialize<T>(T instance)
{
var initializer = typeof(T).GetHiddenConstructorThatDoesntNew(typeof(int), typeof(string));
// call the constructor (int, string) on instance
initializer.Invoke(instance, 7, "Bill");
}
I am aware that I should never really need to do this, I am more wondering if it is possible to re-invoke the constructor/initializer on an already created 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