Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiesmaster/30b10d66ea0678471fb1ea3968344abe to your computer and use it in GitHub Desktop.
Save tiesmaster/30b10d66ea0678471fb1ea3968344abe to your computer and use it in GitHub Desktop.
Possible answer to SO 39451235 (http://stackoverflow.com/q/39451235/471780)
<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