How is CallerMemberName implemented?

I get what it does - it allows us to keep magic strings out of our code - but should it be used over nameof and what is more performant?

Whats the difference/how does CallerMemberName exactly work?

2

There are 2 best solutions below

2
On BEST ANSWER

CallerMemberName is a compile time trick to place the name of the current member in the call to another method. nameof is also a compile time trick to do something similar: it takes the string representation of a member.

Which to use is up to you. I would say: use CallerMemberName where you can, and nameof where you must. CallerMemberName is even more automated than nameof, so that is why I prefer that one.

Both have the same performance implication: only on compile time it takes some extra time to evaluate the code, but that is neglectable.

0
On

[CallerMemberName] and nameof are not completely interchangeable. Sometimes you need first one, sometimes - second one, even when we're talking about the same method:

class Foo : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private string title;

    public string Title
    {
        get { return title; }
        set
        {
            if (title != value)
            {
                title = value;
                // we're using CallerMemberName here
                OnPropertyChanged();
            }
        }
    }

    public void Add(decimal value)
    {
        Amount += value;
        // we can't use CallerMemberName here, because it will be "Add";
        // instead of this we have to use "nameof" to tell, what property was changed
        OnPropertyChanged(nameof(Amount));
    }

    public decimal Amount { get; private set; }
}