C# tip: do not use “is” type, if you will need cast “as” later

 

We have a debate with one of my collegues, is it agood style to check, if the object of particular style, and then cast  as this  type. The perfect answer of Jon Skeet   and answers in Cast then check or check then cast? confirmed my point.

//good
    var coke = cola as CocaCola;
    if (coke != null)
    {
        // some unique coca-cola only code
    }
    //worse
    if (cola is CocaCola)
    {
        var coke =  cola as CocaCola;
        // some unique coca-cola only code here.
    }

Advertisements