Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 502
Eugene Avatar asked Jan 24 '26 20:01

Eugene


1 Answers

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.)

like image 188
Joe Sewell Avatar answered Jan 26 '26 12:01

Joe Sewell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!