How will a C# switch statement's default label handle a nullable enum?

Trey Mack picture Trey Mack · Feb 19, 2013 · Viewed 26.3k times · Source

How will a C# switch statement's default label handle a nullable enum?

Will the default label catch nulls and any unhandled cases?

Answer

Trey Mack picture Trey Mack · Feb 19, 2013

If it's null, it will hit the default label.

public enum YesNo
{
    Yes,
    No,
}

public class Program
{
    public static void Main(string[] args)
    {
        YesNo? value = null;
        switch (value)
        {
            case YesNo.Yes:
                Console.WriteLine("Yes");
                break;
            case YesNo.No:
                Console.WriteLine("No");
                break;
            default:
                Console.WriteLine("default");
                break;
        }
    }
}

The program will print default.

Unless null is handled.

public class Program
{
    public static void Main(string[] args)
    {
        YesNo? value = null;
        switch (value)
        {
            case YesNo.Yes:
                Console.WriteLine("Yes");
                break;
            case YesNo.No:
                Console.WriteLine("No");
                break;
            case null:
                Console.WriteLine("NULL");
                break;
            default:
                Console.WriteLine("default");
                break;
        }
    }
}

prints NULL.

If you have an unhandled enum value that was added later:

public enum YesNo
{
    Yes,
    No,
    FileNotFound,
}

public class Program
{
    public static void Main(string[] args)
    {
        YesNo? value = YesNo.FileNotFound;
        switch (value)
        {
            case YesNo.Yes:
                Console.WriteLine("Yes");
                break;
            case YesNo.No:
                Console.WriteLine("No");
                break;
            default:
                Console.WriteLine("default");
                break;
        }
    }
}

It still prints default.