Link to home
Start Free TrialLog in
Avatar of a_goat
a_goat

asked on

Using Alternate Class Constructors from Constructor

I have something like the following:

class a
{
    public a (int v)
    {
        // Do Something with int
    }

    public a (string v)
    {
       
    }
}

I want to call the constructor which takes the string which needs to try to parse the integer.  If parsing fails it'll use a fall-back value.  Then it'll call the int constructor.

The answer is not something like

    public a (string v) : this(int.Parse(v))
    {
       
    }

because it isn't fault-tolerant
Avatar of tzxie2000
tzxie2000
Flag of China image

please see code below

public a (string v) : this(int.Parse(v))
    {
        try
        {
           this(int.Parse(v));
           return;
        }
        catch(FormatException fe)
        {
        }
        //doing you want to string constructor
    }
ASKER CERTIFIED SOLUTION
Avatar of AvonWyss
AvonWyss
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry, should only be "} catch {" without the parantheses...
I read your question more careful and modify my comment to fit your require

class a
{
   public a(int v)
  {
  //doing init
  }
  public a (string v)
  {
        try
        {
           this(int.Parse(v));
        }
        catch(FormatException fe)
        {
           //set  fall-back value to v
           this(fall-back value);
          //or just call this(0); as any number like 0 is your fall-back value to call.
        }
    }
}
tzxie2000, you cannot call another constructor from within the constructor body. This is only possible before the body of the constructor.
I am very sorry for that mistake
I think the code should be below

class testclass
{
  public testclass(int v):this(v,"",false){}
  public testclass(string v):this(0,v,true){}
  private testclass(int v,string s,bool fromstring)
  {
     if(fromstring)
     {
        try
        {
              v=int.Parse(s);
        }
        catch
       {
           v=0;//set to your fall-back value
        }
    }
    //doing real init;
  }
}
Avatar of a_goat
a_goat

ASKER

I was hoping for something a littel more elegant, but good idea.  I hadn't thought of that one
a_goat, thank you for grading the question. But may I ask what you would have expected to give a higher grade?