Maestro
Maestro

Reputation: 9518

Calling constructor in c# for a second time

Is it possible to call a constructor for a second time, like this:

public ClassName()
{
    Value = 10;
}

public void Reset()
{
    // Reset
    ClassName();
}

Or is this the only way:

public ClassName()
{
    Reset();
}

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

Upvotes: 6

Views: 4442

Answers (3)

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12334

It's not possible to call the constructor two times without using reflection as it's called only once to construct the object.

From MSDN

Instance constructors are used to create and initialize any instance member variables when you use the new expression to create an object of a class.

So you can only go with the second approach.

Upvotes: 3

Konrad Kokosa
Konrad Kokosa

Reputation: 16898

It is possible to call constructor many times by using Reflection because constructor is a kind of special method, so you can call 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 reset object to some default settings, just make some helper, private method for it, called from constructor also:

public ClassName()
{
    Defaults();
}

public void Reset()
{
    Defaults();
}

private void Defaults()
{
    Value = 10;
}

Upvotes: 9

Nilks
Nilks

Reputation: 446

Why would you like to call the constructor multiple times? A constructor is intended to initialize a new object, and therefore is only called upon creation of the object. If you would like to re-use this logic, you will have to put it into a separate method and call it from the constructor. Otherwise you should create a new instance of the object instead, and assign it to the same variable.

Upvotes: 4

Related Questions