Created
February 17, 2015 00:44
-
-
Save JoshVarty/837d223bb76815da7305 to your computer and use it in GitHub Desktop.
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
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