Can expression be used in switch statement?

The new C # 6.0 nameof great in the PropertyChanged template for propagating property changes, using something like:

 private string _myProperty; public string MyProperty { get { return _myProperty; } set { _myProperty= value; OnPropertyChanged(nameof(MyProperty)); } } 

When listening to property changes, I use this (yes, even with ugly hard-coded strings):

  private void OnMyObjectPropertyChanged(object sender, PropertyChangedEventArgs args) { switch (args.PropertyName) { case "MyProperty": DoSomething(); break; } } 

With a new expression name, will this code compile / work?

 private void OnMyObjectPropertyChanged(object sender, PropertyChangedEventArgs args) { switch (args.PropertyName) { case nameof(MyObject.MyProperty): DoSomething(); break; } } 
+6
source share
1 answer

According to this question, the evaluation of the nameof is performed at compile time. This will make it a constant that will work inside switch .

This is confirmed when you look at 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!

+13
source

Source: https://habr.com/ru/post/986726/


All Articles