1

I'm sure there is a better way of doing this but I just want to know why this isn't working. While debugging, the debugger skips over GetAllChildren(

    public static IEnumerable<DependencyObject> GetAllChildren(DependencyObject d)
    {
        if (d.GetType().GetProperties().Any(p => p.Name == "Content"))
        {
            var v = (DependencyObject)(d.GetType().GetProperty("Content").GetValue(d));
            GetAllChildren(v);
            yield return v;
        }
        if (d.GetType().GetProperties().Any(p => p.Name == "Children"))
        {
            foreach (DependencyObject v in (UIElementCollection)d.GetType().GetProperty("Children").GetValue(d))
            {
                yield return v;
                GetAllChildren(v);
            }
        }
    }

1 Answers1

4

This is because you are using yield return with IEnumerable.

Once you iterate over the result of your function, the code will be executed. This is called lazy evaluation and is a key aspect of LINQ, too. To understand deffered execution, read this.

Actually, you have another mistake. Your code wont even return the result of your recursive call. You don't do anything with it. You will have to do this:

yield return v;
foreach (var child in GetAllChildren(v))
{
  yield return child;
}
Mafii
  • 7,227
  • 1
  • 35
  • 55
  • No. You don't seem to understand the basics around IEnumerable, so I recommend to read it up. in short, an IEnumerable says that you can iterate over it. It has only one function, that is GetEnumerator. That enumerator has a moveNext function that the foreach loop "uses". Changing the return type to an enumerator basically doesn't do you any favours at all, rather limits you. Normally you dont return an enumerator. – Mafii Apr 27 '18 at 21:21