-1

I have this code:

    public void myFunction(String label, String type, string command, int attempts = 0)
    {
        try
        {
            Utility.Logger("myFunction attempt " + attempts.ToSafeString() + " label " + label + " type " + type, command);
            ...stuff...
        }
        catch (Exception e)
        {
            if (attempts < 10)
                return myFunction(label, type, command, attempts++);
            else
                return null;
        }
    }

As you can see, I have a recursive call in the catch branch, where I set a parameter a counter = counter + 1.

The weird point is I have always attempts = 0 in my log. Why? What am I missing?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Piero Alberto
  • 3,823
  • 6
  • 56
  • 108
  • 1
    Are you actually falling into catch? And even if you do every time you go in there attempts value is reset zero you passing in.. – JanT Nov 20 '17 at 11:10
  • 1
    `attempts++` will return _old_ value and then increment value by 1. So you are always passing 0 to your recursive function. Change that to `++attempts` or better not use this in such context and just increment outside the function call. – Evk Nov 20 '17 at 11:10

2 Answers2

7

attempts++ increments attempts afterwards, ++attempts does it before recursing.

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
0

Try changing attempts++ to ++attempts.

UPD: oops, took too long.

pgndck
  • 328
  • 1
  • 15