Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
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