How to use CallerMemberName in a CLS compliant assembly
I used the attribute CallerMemberName
in the class implementation INotifyPropertyChanged
as described on MSDN like this:
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
However, using the default parameters is not CLS compliant. But CallerMemberName
can only be used with parameters that have default values ... Is there a commonly used way to resolve this inconsistency without having to call the notification method with a hard-coded string argument?
source to share
I just removed the CallerMemberName
default attribute and parameter value, which means the parameter is no longer optional, so the method signature becomes:
private void NotifyPropertyChanged(String propertyName)
This is then a small (enough) change to trigger it with a statement nameof
providing a string argument:
NotifyPropertyChanged(nameof(FooProperty));
This seems to work pretty well.
I'll leave the question open for a while, however, as others may have better ways or suggest problems with this solution.
source to share