Search code examples
c#switch-statementunreachable-code

How this switch case has unreachable code?


I was implementing some generic IEqualityComparer<T> Equal() method when the code in the switch is unreachable without visible reason for me:

public bool Equals(T x, T y)
{
    switch (nameof(T))
    {
        case nameof(Accessory):
            return (x as Accessory).Id == (y as Accessory).Id;//not reachable
        default:
            return false;
    }
}

Someone has a clue?


Solution

  • nameof evaluates the name of the T at compile time, so it's a constant string, "T", and thus only the default case will ever be taken.

    Here's an alternative implementation:

    public bool Equals(T x, T y)
    {
        if (x is Accessory && y is Accessory)
        {
            var ax = x as Accessory;
            var ay = y as Accessory;
            return ax.Id == ay.Id;
        }
        return false;
    }
    

    C# 7.1 introduces some syntactic sugar:

    public bool Equals(T x, T y)
    {
        if (x is Accessory ax && y is Accessory ay)
        {
            return ax.Id == ay.Id;
        }
        return false;
    }
    

    (Note that your excerpt returns false if both x and y are null; I haven't fixed this in my versions.)