// using Microsoft.CodeAnalysis.CSharp.Syntax; // Suppose we have a statement node "myStatement" MethodDeclarationSyntax enclosingMethod = myStatement.FirstAncestorOrSelf();
bool isInLoop = myStatement.FirstAncestorOrSelfIn this example, we use FirstAncestorOrSelf to check if a statement is inside any of the four loop statement types in C#. We combine four calls to FirstAncestorOrSelf with a logical OR operator to check if any of them return a non-null result. Package/Library: Microsoft.CodeAnalysis.CSharp.Syntax() != null || myStatement.FirstAncestorOrSelf () != null || myStatement.FirstAncestorOrSelf () != null || myStatement.FirstAncestorOrSelf () != null;