Skip to content

Instantly share code, notes, and snippets.

@JoshVarty
Created February 17, 2015 00:44
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 JoshVarty/837d223bb76815da7305 to your computer and use it in GitHub Desktop.
Save JoshVarty/837d223bb76815da7305 to your computer and use it in GitHub Desktop.
var tree = CSharpSyntaxTree.ParseText(@"
class C
{
void M()
{
int variable = 0;
//Does not bind to a symbol (as there is no class called MissingClass)
//but it is not a true nameof expression
MissingClass.nameof(x);
}
}");
var Mscorlib = PortableExecutableReference.CreateFromAssembly(typeof(object).Assembly);
var compilation = CSharpCompilation.Create("MyCompilation",
syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
var model = compilation.GetSemanticModel(tree);
var nameofInvocations = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>();
var validNameOfs = nameofInvocations.Where(n => n.Ancestors().OfType<MemberAccessException>().Count() == 0);
foreach (var validNameOfSyntax in validNameOfs)
{
if (model.GetSymbolInfo(validNameOfSyntax).Symbol == null)
{
//validNameOfSyntax is the nameof operator
Console.WriteLine("We've found a nameof!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment