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
LVL 3
a_goatAsked:
Who is Participating?
 
AvonWyssConnect With a Mentor Commented:
class a {
      private static int ParseIntOrDefault(string value, int def) {
            try {
                  return int.Parse(value);
            } catch () {
                  return def;
            }
      }
      
    public a (int v) {
        // Do Something with int
    }

    public a (string v): this(ParseIntOrDefault(v, 0)) {}
}
0
 
tzxie2000Commented:
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
    }
0
 
AvonWyssCommented:
Sorry, should only be "} catch {" without the parantheses...
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
tzxie2000Commented:
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.
        }
    }
}
0
 
AvonWyssCommented:
tzxie2000, you cannot call another constructor from within the constructor body. This is only possible before the body of the constructor.
0
 
tzxie2000Commented:
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;
  }
}
0
 
a_goatAuthor Commented:
I was hoping for something a littel more elegant, but good idea.  I hadn't thought of that one
0
 
AvonWyssCommented:
a_goat, thank you for grading the question. But may I ask what you would have expected to give a higher grade?
0
All Courses

From novice to tech pro — start learning today.