I suggest a bit redesign your code:
- You've omitted
return in the getInvNo(arg, lengthV-1);
- What if array's item is
null? If we have to skip it as well as empty "" one, string.IsNullOrEmpty is the choice
- Add validation (since method is
protected one I can inherit your class and call the method with any arguments I like)
- Change method into
static
Implementation:
// static: you don't use "this" in the context, and the method is not a virtual one
protected static string getInvNo(string[] arg, int index)
{
// Validation
if (null == arg)
throw new ArgumentNullException("arg");
else if (index >= arg.Length)
index = arg.Length - 1; // or throw ArgumentOutOfRangeException("index");
// Stop conditions:
if (index < 0) // 1. Array exhausted
return "";
else if (!string.IsNullOrEmpty(arg[index])) // 2. We've found non-empty value
return arg[index];
return getInvNo(arg, index - 1);
}
Please, notice that usually we solve such problems without recoursion:
using System.Linq;
...
string result = arg.LastOrDefault(item => !string.IsNullOrEmpty(item)) ?? "";
getInvNo(arg, lengthV-1);toreturn getInvNo(arg, lengthV-1);