Why does the compiler not complain in this case?

this is the code:

 private TreeNode GetTopLevelNode(TreeNode childNode)
    {
        if (childNode == null)
            throw new ArgumentNullException("childNode", "childNode is null.");

        if (childNode.Parent == null) return childNode;

        TreeNode node = childNode;
        while (true)
        {
            if (node.Parent == null)
            {
                return node;
            }
            node = node.Parent;
        }

    }

in a while loop, only if node.Parent == null returns node,

why does the compiler not report the error "not all path codes return a value"?

if 'node.Parent == null' cannot be satisfied, then the node tree will not be returned. The compiler cannot detect this situation?

+3
source share
5 answers

Since you are using while(true){, there is no other way to exit the loop than using return. if node.parent == nullit cannot be done, then it will be an infinite loop. Thus, it is impossible to go past the loop without returning, and the compiler does not complain.

, , , null TreeNode, , ?

: , .

+10

. : , , , .

, , -, . , , ​​ . , (1) , (2) , (3) .

# . , , "while (true)" , "", . , " " " , , ". , " , ", .

+9

. , - , if (node.Parent == null) true.

+1

, .

, wil , - null. , .

+1

, TreeNode , . , , . , , undefined , .

, .

+1

Source: https://habr.com/ru/post/1728144/


All Articles