Created
September 12, 2016 19:48
-
-
Save tiesmaster/30b10d66ea0678471fb1ea3968344abe to your computer and use it in GitHub Desktop.
Possible answer to SO 39451235 (http://stackoverflow.com/q/39451235/471780)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Query Kind="Statements"> | |
<NuGetReference>Microsoft.CodeAnalysis</NuGetReference> | |
<NuGetReference>Microsoft.CodeAnalysis.CSharp</NuGetReference> | |
<Namespace>Microsoft.CodeAnalysis</Namespace> | |
<Namespace>Microsoft.CodeAnalysis.CSharp.Syntax</Namespace> | |
<Namespace>Microsoft.CodeAnalysis.MSBuild</Namespace> | |
<Namespace>Microsoft.CodeAnalysis.CSharp</Namespace> | |
<Namespace>Microsoft.CodeAnalysis.Formatting</Namespace> | |
<Namespace>Microsoft.CodeAnalysis.Text</Namespace> | |
</Query> | |
// possible answer to: http://stackoverflow.com/q/39451235/471780 | |
// create tree, and semantic model | |
var tree = CSharpSyntaxTree.ParseText(@" | |
using System; | |
public class Program | |
{ | |
public static void Main() | |
{ | |
Console.WriteLine(""Hello World""); | |
} | |
}"); | |
var root = tree.GetRoot(); | |
var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); | |
var compilation = CSharpCompilation.Create("SO-39451235", syntaxTrees: new[] { tree }, references: new[] { mscorlib }); | |
var model = compilation.GetSemanticModel(tree); | |
// get the nodes refered to in the SO question | |
var usingSystemDirectiveNode = root.DescendantNodes().OfType<UsingDirectiveSyntax>().Single(); | |
var consoleWriteLineInvocationNode = root.DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); | |
// retrieve symbols related to the syntax nodes | |
var writeLineMethodSymbol = (IMethodSymbol)model.GetSymbolInfo(consoleWriteLineInvocationNode).Symbol; | |
var namespaceOfWriteLineMethodSymbol = (INamespaceSymbol)writeLineMethodSymbol.ContainingNamespace; | |
var usingSystemNamespaceSymbol = model.GetSymbolInfo(usingSystemDirectiveNode.Name).Symbol; | |
// check the namespace symbols for equality, this will return true | |
namespaceOfWriteLineMethodSymbol.Equals(usingSystemNamespaceSymbol).Dump(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment