I do some research on stackoverflow but I can't find the result I need. My problem is "How to determine line code's position of a source file by using Roslyn". For example: I have a source file (named: sample.cs) and content it looks like
using System;
/// <summary>
/// This is summary of namespace
/// </summary>
namespace LearnRoslyn
{
/// <summary>
/// This is summary of class
/// </summary>
public class CodeSample2
{
public SampleClass MyMethod1(int a, int b, SampleClass cls)
{
//This is call method
cls = new SampleClass();
cls.MyMethod4(a);
//This is 3-tier condition
a = (a > b ? 1 : 0);
//This is IF comment
if (a > b && a / b > 1 && b - a == 1)
{
//This is another IF comment
if (a > b || (a / b > 1 && b - a == 1))
{
Console.WriteLine("a > b");
}
}
else
{
if (cls != null)
{
Console.WriteLine("a < b");
}
if (cls.IsNull)
{
Console.WriteLine("a < b");
}
}
return null;
}
public void MyMethod2(int n)
{
n = 2;
}
}
public class SampleClass
{
public bool IsNull { get; set; }
public void MyMethod3(int a, int b)
{
if (a > b)
{
Console.WriteLine("a > b");
}
else
{
Console.WriteLine("a < b");
}
}
public void MyMethod4(int n)
{
n = 2;
}
}
}
As I know, use "CSharpSyntaxWalker" (override Visitor method) to implement that, but I don't know how? How to know the code "if (a > b && a / b > 1 && b - a == 1)", position at line 24 in source file sample.cs? Any suggestion for this situation? Thanks.
Expanding on @George Alexandria's comment, you can get the line number of a node from its syntax tree:
class MyWalker : CSharpSyntaxWalker
{
public override void Visit(SyntaxNode node)
{
FileLinePositionSpan span = node.SyntaxTree.GetLineSpan(node.Span);
int lineNumber = span.StartLinePosition.Line;
// Do stuff with lineNumber.
// ...
}
// ...
}
See SyntaxTree.GetLineSpan
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With