Our goal is to build a toy abstract syntax tree for C# classes using Roslyn. We just want to show the basic structure of a class instead of walking through the entire AST. For example (Taken from MSDN):
class TimePeriod
{
private double seconds;
public double Hours
{
get { return seconds / 3600; }
set { seconds = value * 3600; }
}
}
Let us only consider the Property Hours; we are only interested in extracting the tokens for modifier (public), return type (double), identifier (Hours) as for the body of two accessors we want to directly extract it as a String.
However, as we walk though the roslyn (shown in the screen dump) when we get to get accessor's body we did not find the field representing the entire string. What's the correct way of achieving this?
The obvious way is to call ToString:
Returns the string representation of this node, not including its leading and trailing trivia.
If you want the leading and trailing trivia (whitespace, comments, ...), there's ToFullString:
Returns full string representation of this node including its leading and trailing trivia.
For efficiency purposes, you may also be interested in the WriteTo method, which writes what ToFullString would produce to a TextWriter, avoiding intermediate string allocations:
Writes the full text of this node to the specified TextWriter.
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