Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CallerMemberNameAttribute and Roslyn

Tags:

c#

roslyn

Does Roslyn CTP support CallerMemberNameAttribute and others similar?

I have a method with several parameters, some obligatory, and also there is a parameter with default value, marked with CallerMemberName attribute.

I am generating a call of this method by Roslyn, passing only obligatory parameters, and expecting it to generate values for compiler-generated parameters too, but this does not happen, they have default values.

Is this a limitation of Roslyn's current version, or I am doing something wrong?

like image 313
Mikhail Brinchuk Avatar asked May 03 '26 14:05

Mikhail Brinchuk


1 Answers

In the What's New in the Microsoft "Roslyn" September 2012 CTP, it is noted that:

The full C# 4 and Visual Basic 10 languages are supported by the parser, but there are several language features that are not yet completely implemented in the current Roslyn compilers.

The Caller Information feature is introduced in .NET Framework 4.5 (C# 5.0 and Visual Basic 11). Therefore, Roslyn does not support it in the current version. However obtaining caller information could be accomplished using something like the following code snippet from "Can I get function caller/callee information from Roslyn?" question asked in MSDN forums:

var syntaxTree = SyntaxTree.ParseCompilationUnit(code);

var semanticModel = Compilation.Create("compilation")
    .AddSyntaxTrees(syntaxTree)
    .AddReferences(new AssemblyFileReference(typeof(object).Assembly.Location))
    .GetSemanticModel(syntaxTree);

var baz = syntaxTree.Root
    .DescendentNodes()
    .OfType<ClassDeclarationSyntax>()
    .Single(m => m.Identifier.ValueText == "C1")
    .ChildNodes()
    .OfType<MethodDeclarationSyntax>()
    .Single(m => m.Identifier.ValueText == "Baz");

var bazSymbol = semanticModel.GetDeclaredSymbol(baz);

var invocations = syntaxTree.Root
    .DescendentNodes()
    .OfType<InvocationExpressionSyntax>();

var bazInvocations = invocations
    .Where(i => semanticModel.GetSemanticInfo(i).Symbol == bazSymbol);
like image 79
Alireza Maddah Avatar answered May 06 '26 05:05

Alireza Maddah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!