2

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?

Mafii
  • 7,227
  • 1
  • 35
  • 55
  • 3
    They are for two unrelated scenarios. `CallerMemberName` tells you who is calling you, `nameof` tells you who you are calling. – GSerg Jun 21 '16 at 11:13
  • 2
    I think the question is: should I provide a method with a member name using `nameof`, or should I depend on `CallerMemberName` to do it for me? – Patrick Hofman Jun 21 '16 at 11:15
  • @PatrickHofman true, ill edit – Mafii Jun 21 '16 at 11:16

2 Answers2

4

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.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
4

[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; }
}
Dennis
  • 37,026
  • 10
  • 82
  • 150