I'm trying to write a recursive function in C# that will take two arguments, an Array, and an index. The index should change on each recursion, but start being the length of the Array - 1.
Like this:
public static int[] UpArray(int[] num, int i = num.Length - 1) {...}
However, I cannot reference num. I could pass along a boolean stating whether this is the first time through or not and include an if-clause in the code. But I was wondering if there was a more elegant way.
No, the default value for an optional parameter has to be a constant.
You could use -1
as the default value as suggested in comments, or make it a nullable int and default it to null:
public static int[] UpArray(int[] num, int? index = null)
{
int realIndex = index ?? num.Length - 1;
...
}
Or better yet, just have two methods:
public static int[] UpArray(int[] num)
{
return UpArray(num, num.Length - 1);
}
private static int[] UpArray(int[] num, int index)
{
...
}
That's assuming you don't want the external caller to actually specify the index - you just want to do that on the recursive calls.
No need for any optional parameters, and the overall API is what you really want, rather than it letting implementation details peek through.
See more on this question at Stackoverflow