Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling constructor in c# for a second time

Tags:

c#

constructor

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;
}
like image 986
Maestro Avatar asked Dec 09 '14 13:12

Maestro


People also ask

How do you call a constructor?

The this keyword in Java is a reference to the object of the current class. Using it, you can refer a field, method or, constructor of a class. Therefore, if you need to invoke a constructor explicitly you can do so, using "this()".

How do you call a class constructor?

Calling a Constructor You call a constructor when you create a new instance of the class containing the constructor. Here is a Java constructor call example: MyClass myClassVar = new MyClass(); This example invokes (calls) the no-argument constructor for MyClass as defined earlier in this text.

What does it mean to call a constructor?

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.


1 Answers

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;
}
like image 95
Konrad Kokosa Avatar answered Sep 19 '22 01:09

Konrad Kokosa