Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what circumstances can the C# 'is' keyword throw an exception?

I stumbled upon something like the following in our code base...

    protected bool IsThing(object item)
    {
        try
        {
            return item is Thing;
        }
        catch (Exception)
        {
            return false;
        }
    }

I'm trying to work out if there is any circumstance in which this catch will ever be visited?

like image 514
gingerbreadboy Avatar asked Dec 02 '22 17:12

gingerbreadboy


1 Answers

The is keyword never throws an exception. That is a useless method and you should remove it.

if(IsThing(item)) {...} could and should be replaced with if(item is Thing) { ... }

like image 136
dcastro Avatar answered Dec 04 '22 06:12

dcastro