Constructor call in C # for the second time

Is it possible to call the constructor a second time, for example:

public ClassName() { Value = 10; } public void Reset() { // Reset ClassName(); } 

Or is this the only way:

 public ClassName() { Reset(); } public void Reset() { // Reset Value = 10; } 
+6
source share
3 answers

You can invoke the constructor many times using Reflection, because the constructor is a kind of special method, so you can name it as a method.

 public void Reset() { this.GetType().GetConstructor(Type.EmptyTypes).Invoke(this, new object[] { }); } 

HENCE : this is not how you should do it . If you want to use the reset object for some default settings, just create an auxiliary, private method for it, also called from the constructor:

 public ClassName() { Defaults(); } public void Reset() { Defaults(); } private void Defaults() { Value = 10; } 
+7
source

Why do you want to call the constructor several times? The constructor is intended to initialize a new object and therefore is intended only to create an object. If you want to reuse this logic, you will have to put it in a separate method and call it from the constructor. Otherwise, you should create a new instance of the object and assign it to the same variable.

+3
source

It is not possible to call the constructor twice without using reflection, because it called only once to construct the object.

From MSDN

Instance constructors are used to create and initialize any instance member variables when using a new expression to create a class object.

So, you can only go with the second approach.

+3
source

Source: https://habr.com/ru/post/979330/


All Articles