Mercury
Mercury

Reputation: 732

Run function on creation of class instance C#

I have a pice of initialiser code that should run when a new instance of a class is created, without having to be called. How would I do that ?

Update:

class Pice {

  public int Type;

  public void init() {

   Type = random(sudo);

  }

}

Now I would like the init to run only once when an instance of the class is created. So where do I put it ?

Upvotes: 1

Views: 5150

Answers (3)

parameter
parameter

Reputation: 634

Format this to fit your class name, paste into your class.cs file, and add your initialization logic.

public ClassName() {
    // initialization logic goes here
}

See this page for additional information.

Upvotes: 0

Giorgi_Mdivani
Giorgi_Mdivani

Reputation: 383

class Pice {

 public Pice(){
  this.init();
}

  public int Type;

  public void init() {

   Type = random(sudo);

  }

}

Upvotes: -1

Wheels73
Wheels73

Reputation: 2890

Use the class constructor.

 public class MyClass
        {
            public MyClass() 
            {
                //Initialise
            }
        }

Upvotes: 12

Related Questions