I am sure I am making a foolish mistake here but it beats me. Here is a piece of code:
void Main()
{
//Key is a parent while the list contains its children
Dictionary<string,List<string>> d = new Dictionary<string,List<string>>();
d.Add("1",new List<string>(){"2","3"});//valid.should return false
d.Add("2",new List<string>(){"4"});//valid.should return false
d.Add("3",new List<string>(){"5"});//valid.should return false
d.Add("4",new List<string>(){"1"});//invalid.should return true
IsChildAlreadyAParent("4","2",d);
}
private bool IsChildAlreadyAParent( string child, string parent, Dictionary<string, List<string>> d )
{
if( !d.ContainsKey( child ) || ( d.ContainsKey( child ) && d[child].Count == 0 ))
{
return false;
}
foreach( string childOfChild in d[child] )
{
if( childOfChild == parent )
return true;
if( IsChildAlreadyAParent( childOfChild, parent, d ) ) return true;
}
}
Compiling this gives me this error:
IsChildAlreadyAParent(string, string, System.Collections.Generic.Dictionary<string,System.Collections.Generic.List<string>>)': not all code paths return a value
I have read the code a few times and I cant see how a return condition would be missed. I know I can rectify it by adding a method return statement before the method end but it doesn’t help me understand the issue at hand. Where is the gap??
You might think this executes the loop body exactly once, always returning from the function:
But what if
d[child]has no elements at all?Also, testing only the first child probably isn’t the right solution either.
Better: