1

i made this recursive function, but after the "return" it jumps back to the line GetProp(classes, obj); and so it returns twice and I get a wrong value.

Thats how I call the method

foreach (string fieldKey in fieldKeys)
{
   Console.WriteLine(fieldKey);
   var props = fieldKey.Split('.');
   form.SetField(fieldKey, GetProp(props, inv));
}

Here is the method

public static string GetProp(string[] classes, object oldObj)
{
     var obj = oldObj.GetType().GetProperty(classes[0]).GetValue(oldObj, null);
     if(classes.Length>1)
     {
        classes = classes.Skip(1).ToArray();
        GetProp(classes, obj);
     }
        return obj.ToString();
}
3
  • I think you need to add a return keyword before GetProp(classes, obj); inside your if statement. Commented Mar 23, 2018 at 10:16
  • It does not return twice, it returns once on the return line, but you don't do anything with the result from the recursive call not sure what your business logic is, but inside the if shouldn't it be return GetProp(classes, obj); ? This would prevent the last return from executing Commented Mar 23, 2018 at 10:16
  • Thanks guys! How couldn't I see that.. Time for weekend Commented Mar 23, 2018 at 10:18

3 Answers 3

1

You need the return at recursion i think.

 public static string GetProp(string[] classes, object oldObj)
 {
 var obj = oldObj.GetType().GetProperty(classes[0]).GetValue(oldObj, null);
 if(classes.Length>1)
   {
    classes = classes.Skip(1).ToArray();
    return GetProp(classes, obj);
   }
      return obj.ToString();
 }
Sign up to request clarification or add additional context in comments.

Comments

0

You need return the string when use recursive.

example:

public int recursive(int i){
    if(i == 1){
       i = i + 1;
       return recursive(i);
    }
    return i;
}

try with

return GetProp(classes, obj);

Comments

0

it doesn't jump this actually the most recent call returns to main call any way to fix this you need to return the most recent value just change GetProp(classes,object); to return GetProp(classes,object);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.