9

I would like to understand how this particular case works. Here is the shot from msdn article where INotifyPropertyChanged interface is explained (https://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=EN-US&k=k%28System.ComponentModel.INotifyPropertyChanged%29;k%28TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5%29;k%28DevLang-csharp%29&rd=true) enter image description here

As it's said in marked lines there is a way of intercepting method call to substitute a value instead of what is actual goes as a parameter? I would like to get an idea of what the code to do this looks like. I know how to work with attributes set for properties and other class members but this use case is not clear for me.

Thanks.

2
  • Similar question: How to use method parameter attributes Commented Nov 20, 2015 at 13:18
  • I don't think it is a similar question. I've read that post. There is asked how to validate value of a parameter for which custom attribute is set. Jon Skeet answered it is not possible. Here I'm asking for an example of code to understand implemented solution as for INotifyPropertyChanged interface. Commented Nov 20, 2015 at 13:22

1 Answer 1

4

It seems to be a feature implemented in the compiler: it knows about this special attribute and it substitutes the name of the caller into the optional argument when it has its default value.

If you want you can check the Roslyn implementation. Although it is not always very straightforward to navigate there seems to be something here in the GetDefaultParameterValue function (starting at line 844, at least in the current revision as of the time of writing -- 0db946b):

if the optional parameter is annotated with <see cref="CallerLineNumberAttribute"/>, <see cref="CallerFilePathAttribute"/> or <see cref="CallerMemberNameAttribute"/>, and there is no explicit argument corresponding to it, we will provide caller information as a value of this parameter.

At line 912 there is an else if clause that handles this case (the if and else if clauses before that handle the similar new features CallerLineNumberAttribute and CallerFilePathAttribute):

...
else if (parameter.IsCallerMemberName && ((callerSourceLocation = GetCallerLocation(syntax, enableCallerInfo)) != null))
...

which is eventually used to bind the parameter:

BoundExpression memberNameLiteral = MakeLiteral(syntax, ConstantValue.Create(memberName), _compilation.GetSpecialType(SpecialType.System_String));
defaultValue = MakeConversion(memberNameLiteral, parameterType, false);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.