Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use an nameof expression in switch statement?

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;
    }
}
like image 632
Rogier Avatar asked May 07 '15 09:05

Rogier


1 Answers

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!

like image 156
Patrick Hofman Avatar answered Sep 19 '22 20:09

Patrick Hofman