How to exit C # recursive method with return type

My code is similar to below,

public object GetObjectValue(object obj, int condition)
{
     if(condition > 10)
     {
       //exit from method 
       // return; gives compiler error.      
     }
     else
     {
        GetObjectValue(obj,condition); // like this i need to use recursive call.
        //Do stuffs
     }
}

How to get out of this method. Help me.

+3
source share
4 answers

Some moments:

  • You need to return something anyway. Even if you're return nullon if(condition > 10), your next compilation error will say that you need to return a value on each path (in fact, the same compilation error)
  • GetObjectValue(obj,condition); can lead to infinite recursion - you name it with the same values ​​again and again.
  • " " return, ( finally, ). , return , , , -: object returnedValue = GetObjectValue(obj, condition);

, - :

public object GetObjectValue(object obj, int condition)
{
     if(condition > 10)
     {
       //exit from method 
       return null; 
     }
     else
     {
        IChild current = (IChild)obj
        //Do stuffs HERE
        return GetObjectValue(current.Parent, condition + 1);  recursive call.
     }
}
+8

null.

public object GetObjectValue(object obj, int condition) {
    if (condition > 10) {
        return null;
    } else {
        return GetObjectValue(obj, condition);
    }
}

, , condition 10 . , , .

public object GetObjectValue(object obj, int condition) {
    if (condition > 10) {
        return null;
    } else {
        return GetObjectValue(obj, condition++);
    }
}

condition , , 10, . , ; , null.

+4

It is supposed to return an object:

public object GetObjectValue(object obj, int condition)

Or change the return type:

public void GetObjectValue(object obj, int condition)

Or use a valid return statement:

if(condition > 10)
 {
   //exit from method 
   return null;
 }
+1
source

You specified the return type as an object, so you must specify a valid return type. Try changing the code below

public object GetObjectValue(object obj, int condition)
{
    if (condition <= 10)
    {
        GetObjectValue(obj, condition);
    }
    return null;   //return whatever object you have to return
}
+1
source

All Articles