views:

61

answers:

2

The following code snippet is from the Silverlight SDK and I am trying to understand the reason it is the way it is. Can anyone explain the need for the for loop?

 internal static DependencyObject GetVisualRoot(DependencyObject d)
        { 
            DependencyObject root = d; 
            for (; ; )
            { 
                FrameworkElement element = root as FrameworkElement;
                if (element == null)
                { 
                    break;
                }

                DependencyObject parent = element.Parent as DependencyObject; 
                if (parent == null)
                { 
                    break;
                }

                root = parent;
            }
            return root; 
        }
+1  A: 

It's probably Microsoft style of defining infinite loop.

The loop will traverse through each parent until it failed to cast.

Adrian Godong
+2  A: 

It's walking up the tree looking for any element that is either parentless or not a FrameworkElement. The loop is an unrolled tail recursion. A while(true) loop would have been fine too.

Patrick