KentZhou
KentZhou

Reputation: 25553

How to call constructor inside the class?

I want to call constructor inside the class like: public class Myclass(){

   public MyClass(){
      //......
   }

   public MyClass(int id):this(){
      //......
   }

   private void Reset(){
      //.....
      this = new MyClass(id);    //here I want to call constructor
      //......
   }
}

but it is not working. Is it possible and how can I do it if Yes?

Upvotes: 10

Views: 22520

Answers (5)

Chris Hannon
Chris Hannon

Reputation: 4134

Within a class you can't reassign this (although it's worth noting that within a struct it's perfectly legal). The question, though, is whether you should. I assume that your goal is to set all field values to a specific state, so as other people have already said you can either have your Reset method return a new instance or you can break out your logic into a Clear() method and call that instead.

Upvotes: 1

Timothy Carter
Timothy Carter

Reputation: 15785

You can't. But what you could do is split the constructor logic into an Initialize method that then reset could call.

   public MyClass(){
   //......
   }

   public MyClass(int id):this(){
      Initialize(id);
   }

   private void Initialize(int id){
   //....
   }

   private void Reset(){
      //.....
      Initialize(id);
      //......
   }
}

Upvotes: 13

James Michael Hare
James Michael Hare

Reputation: 38397

You can call a constructor for your class inside your class (in fact this is often done with factory methods):

public class MyClass
{
    public static MyClass Create()
    {
        return new MyClass();   
    }
}

But you can't change the value of the this reference inside the class. You should instead have your "Reset()" method set the fields back to their default values.

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245429

Simple answer: You can't.

Slightly more complicated answer: Move your initialization logic into a separate method that can be called from the constructor and your Reset() method:

public class MyClass
{
    public int? Id { get; }

    public MyClass()
    {
        Initialize();
    }

    public MyClass(int id)
    {
        Initialize(id);
    }

    public Reset()
    {
        Initialize();
    }

    private Initialize(int? id = null)
    {
        // initialize values here instead of the constructor
        Id = id;
    }
}

Upvotes: 16

Wouter de Kort
Wouter de Kort

Reputation: 39898

No this is not possible. You cannot assign to this.

You could however let Reset() return a new instance of MyClass so the caller code could say:

public class MyClass
{
    public MyClass Reset()
    {
        return new MyClass();
    }
}

MyClass c = new MyClass();
c = c.Reset();

Or you could implement the Reset method in such a way that all fields are reinitialized to their default values.

Upvotes: 3

Related Questions