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

Posted by Michael Freidgeim on Geeks with Blogs See other posts from Geeks with Blogs or by Michael Freidgeim
Published on Sat, 09 Jun 2012 08:35:19 GMT Indexed on 2012/06/09 10:41 UTC
Read the original article Hit count: 698

Filed under:

 

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

© Geeks with Blogs or respective owner