Search code examples
c#.netroslynnameof

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;
    }
}

Solution

  • 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!