Search code examples
c#-6.0default-parameterscls-compliant

How to use CallerMemberName in a CLS compliant assembly


I have used the CallerMemberName attribute in a class's implementation of INotifyPropertyChanged as described on MSDN as follows:

    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 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 solve this inconsistency without having to call the notify method with a hard-coded string argument?


Solution

  • I have simply removed the CallerMemberName attribute and the default parameter value, meaning the parameter is no longer optional, so the method signature becomes:

    private void NotifyPropertyChanged(String propertyName)
    

    Then it is a small (enough) change to call it with the nameof operator providing the string argument:

    NotifyPropertyChanged(nameof(FooProperty));
    

    This seems to work quite well.

    I will leave the question open for a little while however as others may have better ways, or suggest problems with this solution.