0

In C# 4.0 I am doing the following:

public string PropertyA
{
  get;
  set
  {
    DoSomething("PropertyA");
  }
}

public string PropertyB
{
  get;
  set
  {
    DoSomething("PropertyB");
  }
}

..I have a lot of these properties and doing it manually will be a pain. Is there a way I could replace this with:

public string PropertyA
{
  get;
  set
  {
    DoSomething(GetNameOfProperty());
  }
}

..maybe using reflection?

John 'Mark' Smith
  • 2,564
  • 9
  • 43
  • 69
  • 2
    It doesn't help much now, but C# 6 will feature a `nameof` operator, which will do something similar to what you are looking for, and with compile-time checking. (Presumeably, you'll still have to write the property name twice everywhere, but the compiler will tell you if you misspelt it somewhere.) – O. R. Mapper Sep 03 '14 at 12:09
  • Sounds like an XY problem - What problem are you trying to solve by doing this? – Sayse Sep 03 '14 at 12:10
  • 2
    @Sayse Doesn't sound like it to me. This is a common pattern for implementing `INotifyPropertyChanged`. –  Sep 03 '14 at 12:11
  • @hvd - Ah very true, its been a while since I implemented that – Sayse Sep 03 '14 at 12:12
  • If you're targeting .NET Framework 4.5 you can use [CallerMemberNameAttribute](http://msdn.microsoft.com/ru-ru/library/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx) – Ivan Zub Sep 03 '14 at 12:14
  • See [this](http://stackoverflow.com/a/14849434/1244816), it works i .Net 4.0 – Jens Kloster Sep 03 '14 at 12:14

3 Answers3

2

In .NET 4.5 your DoSomething method should use the [CallerMemberName] parameter attribute:

void DoSomething([CallerMemberName] string memberName = "")
{
    // memberName will be PropertyB
}

Then just call it like this:

public string PropertyA
{
     get
     {
         ...
     }
     set
     {
         DoSomething();
     }
}

See MSDN on this.

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

There is no way to do this in current C# versions, reflection won't help. You could hack this with expressions and get compile time checking, but that's about it, you'd have to type even more code too

 DoSomething(()=>this.PropertyA); // have dosomething take an expression and parse that to find the member access expression, you'll get the name there

A good alternative if that's possible for you would be to use Postsharp to do this instead in a clean way, but that may not always be possible.

Ronan Thibaudau
  • 3,413
  • 3
  • 29
  • 78
0

You can use reflection of GetCurrentMethod.

public string PropertyA
{
    get;
    set
    {
        DoSomething(MethodBase.GetCurrentMethod().Name.Substring(4));
    }
}

It's available for .Net 4.

As @hvd explains, the Name will return set_PropertyA, then use Substring to take the property name.

Yuliam Chandra
  • 14,494
  • 12
  • 52
  • 67