The new C# 6.0 nameof
is great in the PropertyChanged
pattern for propagating property changes using something like:
private string _myProperty;
public string MyProperty
{
get
{
return _myProperty;
}
set
{
_myProperty= value;
OnPropertyChanged(nameof(MyProperty));
}
}
When listening of property changes I use this (yes, even with ugly hardcoded strings):
private void OnMyObjectPropertyChanged(object sender, PropertyChangedEventArgs args)
{
switch (args.PropertyName)
{
case "MyProperty":
DoSomething();
break;
}
}
With the new nameof expressions would this code compile / work?
private void OnMyObjectPropertyChanged(object sender, PropertyChangedEventArgs args)
{
switch (args.PropertyName)
{
case nameof(MyObject.MyProperty):
DoSomething();
break;
}
}
According to this question, the evaluation of the nameof
keyword is done on compile time. This will make it a constant, which will work inside switch
statements.
This is proven when you look to the compiled output of this code:
using System;
public class Program
{
public string A { get; set; }
public static void Main()
{
string a = "A";
switch (a)
{
case nameof(Program.A):
{
Console.WriteLine("Yes!");
break;
}
}
}
}
Output:
Yes!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With