CallerMemberName in .NET 4.0 not working

Pradeep picture Pradeep · Sep 17, 2013 · Viewed 26k times · Source

I am trying to use CallerMemberName attribute in .NET 4.0 via BCL portability pack. It is always returning an empty string instead of the member name. What am I doing wrong?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        MessageBox.Show(new class2().CallMe);
    }
}

public class class2
{
    public string CallMe 
    {
        get
        {
            return HelpMe();
        }
    }

    private string HelpMe([CallerMemberName] string param = "")
    {
        return param;
    }
}

Answer

user3734274 picture user3734274 · Aug 11, 2016

Targeting 4.0 works just fine if you add:

namespace System.Runtime.CompilerServices {
    sealed class CallerMemberNameAttribute : Attribute { }
}