Skip to content

Instantly share code, notes, and snippets.

@UtsavChokshiCNU
Created November 2, 2017 12:23
Show Gist options
  • Save UtsavChokshiCNU/5dee7b7ad2158db2ac436702145c75d0 to your computer and use it in GitHub Desktop.
Save UtsavChokshiCNU/5dee7b7ad2158db2ac436702145c75d0 to your computer and use it in GitHub Desktop.
C# Roslyn Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace GettingStartedCS
{
class RoslynTry
{
static void Main(string[] args){
SyntaxTree tree = CSharpSyntaxTree.ParseText(
@"using System;
using System.Collections;
using System.Linq;
using System.Text;
#define TEST_1_0
#define TEST_1_1
namespace HelloWorld
{
[CompilerGenerated()]
class Program
{
public static String s1 {get; set;} = ""utsav"";
public int s2 => s1.Length;
static void Main(string[] args)
{
String s = null;
int? i = s?.Length;
#if TEST_1_0
int TEST_1_0 = 1;
#if TEST_1_1
int TEST_1_1 = 1;
#endif
}
}
}");
var root = (CompilationUnitSyntax)tree.GetRoot();
var firstMember = root.Members[0];
Console.WriteLine(firstMember.ToString());
var helloWorldDeclaration = (NamespaceDeclarationSyntax)firstMember;
var programDeclaration = (ClassDeclarationSyntax)helloWorldDeclaration.Members[0];
Console.WriteLine(programDeclaration.AttributeLists.ToArray().ToString());
//Checking initial value of property is accessible or not ? : Yes it is
var propDeclaration1 = (PropertyDeclarationSyntax)programDeclaration.Members[0];
Console.WriteLine(propDeclaration1.Initializer.Value.ToString());
//Checking lambda operator works with property declaration ? : Yes it is
var propDeclaration2 = (PropertyDeclarationSyntax)programDeclaration.Members[1];
Console.WriteLine(propDeclaration2.Modifiers.ToString());
Console.WriteLine(propDeclaration2.ExpressionBody.Expression);
//Checking preprocessing directives is properly logged or not ? : Yes it is
var mainDeclaration = (MethodDeclarationSyntax)programDeclaration.Members[2];
Console.WriteLine(mainDeclaration.Body.GetFirstDirective().ToString());
Console.WriteLine(mainDeclaration.Body.GetLastDirective().ToString());
//Checking null conditional operator is detected ? : Yes it is
var localDeclaration = (LocalDeclarationStatementSyntax)mainDeclaration.Body.Statements.ToArray()[1];
var varDeclaration = (VariableDeclarationSyntax)localDeclaration.Declaration;
Console.WriteLine(((EqualsValueClauseSyntax)varDeclaration.Variables.ToArray()[0].Initializer));
}
}
}
@UtsavChokshiCNU
Copy link
Author

Before running this file,
Install following packages using nuget :

  • Microsoft.Net.Compilers
  • Microsoft.CodeAnalysis

For more information , check : official github repository for roslyn

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment