This website stores cookies. Click here to accept them.cookie information page

How do you call one constructor from another?

22nd July 2012

You would think that this would be pretty straightfoward in c# to call one class constructor from another with a different function signature.. what about:

class Animaux
{
  public Animaux()
  {
    this("george");
  }

  public Animaux(string animalName)
  {
     //.... do some things
  }
}

Unfortunately c# won't allow that; you must have:

 

class Animaux
{
  public Animaux() :     this("george") {}
  }

  public Animaux(string animalName)
  {
     //.... do some things
  }
}

 

In PHP you can't have multiple function signatures, so you would just have:

class Animaux

{

  function Animaux($animalName='')
  {
    if($animalName=='') $animalName='george';
  } 

}

.. which at least makes a bit more sense....


Add your comment for "How do you call one constructor from another?":

© Alberon Ltd 2017

8 Standingford House
26 Cave Street
Oxford
OX4 1BA

01865 596 144

Oxford Web is a trading name of Alberon Ltd, registered company no. 5765707 (England & Wales).