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.
Some points:
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)GetObjectValue(obj,condition);
may result in an infinite recursion - you call it with the same values over and over.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.
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With