Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit from a C# recursive method which has return type

Tags:

c#

recursion

My code is like the below one,

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 exit from this method. Help me.

like image 231
Thaadikkaaran Avatar asked May 12 '11 05:05

Thaadikkaaran


2 Answers

Some points:

  1. You need to return something in either case. Even if you return null on if(condition > 10), your next compilation error will say you need to return a value on every path (actually, that's the same compilation error)
  2. GetObjectValue(obj,condition); may result in an infinite recursion - you call it with the same values over and over.
  3. You cannot "do stuff" after a return statement - that marks the end of the executed code (unless you have a finally block, but that's another subject). If you don't want to return that value that's also great, but you probably want to use it somehow: object returnedValue = GetObjectValue(obj, condition);

You may be looking for something like:

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.
     }
}
like image 117
Kobi Avatar answered Oct 12 '22 23:10

Kobi


You need to return an object reference, or null.

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

Be aware though, that this method is very prone to a stack overflow error because any value of condition less than or equal to 10 will never reach the base case, or terminating condition. Recursive methods need a case that returns a value without calling itself.

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

Now condition is incremented, so when the method is called, it will eventually progress towards a value greater than 10, satisfying the condition and returning null. This is still a useless method though, because it can only ever return the same value for any input; the only difference will be how many recursive calls it makes before returning null.

like image 26
Quick Joe Smith Avatar answered Oct 13 '22 00:10

Quick Joe Smith