C# attribute to pass in name of the property a computed value will be assigned to

Viewed 209

I have created a helper method that parses values from an XML node, but at this moment I have to pass in the name of the property to value has to be assigned to.

I know of the [CallerMemberName] attribute, but I wonder whether there is an attribute that can be used to automatically get the Property name the value will be assigned to.

For example:

Current situation

I have this extension method:

public static string GetStringValueOrDefault(this XmlNode node, string elementName) =>
    node[elementName]?.InnerText ?? default;

Which is called like this:

PrinterSettings.PrinterName = printerSettingsElement.GetStringValueOrDefault(nameof(PrinterSettings.PrinterName))

Desired situation

The same extension method, with an attribute:

public static string GetStringValueOrDefault(this XmlNode node, [AssigneeName] string elementName) =>
    node[elementName]?.InnerText ?? default;

I made up the [AssigneeName] attribute, but I guess you get the idea.

Which should be called like this, which is much cleaner:

PrinterSettings.PrinterName = printerSettingsElement.GetStringValueOrDefault()
1 Answers

TL;DR: there isn't.

And there cannot be in general. And if it only works in some cases then what would the hypothetical AssigneeNameAtttribute do when there is no property being assigned to?

Consider:

var temp = doc.GetStringValueOrDefault();
outputDoc.Prop = temp;

Not only is temp not helpful for the elementName parameter value of GetStringValueOrDefault it is likely to be removed by the optimiser leading to different behaviour depending on compilation settings.

Unlike CallerMemberNameAttribute – there is always a caller – the assignee may not exist is any useful format. Consider another case:

var results = doc.Elements()
                  .Select(e => new { e.Name, Value = e.GetStringValueOrDefault())
                  .ToList();
Related