APISampleUnitTestsCS.FAQ.GetLineAndColumnInfo C# (CSharp) Method

GetLineAndColumnInfo() private method

private GetLineAndColumnInfo ( ) : void
return void
        public void GetLineAndColumnInfo()
        {
            var tree = SyntaxTree.ParseText(@"
            class Program
            {
            public static void Main()
            {
            }
            }", "MyCodeFile.cs");

            // Get BlockSyntax corresponding to the method block for 'void Main()' above.
            var node = (BlockSyntax)tree.GetRoot().DescendantNodes().Last();

            // Use GetLocation() and GetLineSpan() to get file, line and column info for above BlockSyntax.
            Location location = node.GetLocation();
            FileLinePositionSpan lineSpan = location.GetLineSpan(usePreprocessorDirectives: false);
            Assert.IsTrue(location.IsInSource);
            Assert.AreEqual("MyCodeFile.cs", lineSpan.Path);
            Assert.AreEqual(4, lineSpan.StartLinePosition.Line);
            Assert.AreEqual(4, lineSpan.StartLinePosition.Character);

            // Alternate way to get file, line and column info from any span.
            location = tree.GetLocation(node.Span);
            lineSpan = location.GetLineSpan(usePreprocessorDirectives: false);
            Assert.AreEqual("MyCodeFile.cs", lineSpan.Path);
            Assert.AreEqual(4, lineSpan.StartLinePosition.Line);
            Assert.AreEqual(4, lineSpan.StartLinePosition.Character);

            // Yet another way to get file, line and column info from any span.
            lineSpan = tree.GetLineSpan(node.Span, usePreprocessorDirectives: false);
            Assert.AreEqual("MyCodeFile.cs", lineSpan.Path);
            Assert.AreEqual(5, lineSpan.EndLinePosition.Line);
            Assert.AreEqual(5, lineSpan.EndLinePosition.Character);

            // SyntaxTokens also have GetLocation().
            // Use GetLocation() to get the position of the '{' token under the above BlockSyntax.
            SyntaxToken token = node.DescendantTokens().First();
            location = token.GetLocation();
            lineSpan = location.GetLineSpan(usePreprocessorDirectives: false);
            Assert.AreEqual("MyCodeFile.cs", lineSpan.Path);
            Assert.AreEqual(4, lineSpan.StartLinePosition.Line);
            Assert.AreEqual(4, lineSpan.StartLinePosition.Character);

            // SyntaxTrivia also have GetLocation().
            // Use GetLocation() to get the position of the first WhiteSpaceTrivia under the above SyntaxToken.
            SyntaxTrivia trivia = token.LeadingTrivia.First();
            location = trivia.GetLocation();
            lineSpan = location.GetLineSpan(usePreprocessorDirectives: false);
            Assert.AreEqual("MyCodeFile.cs", lineSpan.Path);
            Assert.AreEqual(4, lineSpan.StartLinePosition.Line);
            Assert.AreEqual(0, lineSpan.StartLinePosition.Character);
        }