Cast then check or check then cast?

Posted by jamesrom on Stack Overflow See other posts from Stack Overflow or by jamesrom
Published on 2010-03-31T05:11:02Z Indexed on 2010/03/31 5:13 UTC
Read the original article Hit count: 635

Filed under:
|
|
|

Which method is regarded as best practice?

Cast first?

public string Describe(ICola cola)
{
    var coke = cola as CocaCola;
    if (coke != null)
    {
        string result;
        // some unique coca-cola only code here.
        return result;
    }
    var pepsi = cola as Pepsi;
    if (pepsi != null)
    {
        string result;
        // some unique pepsi only code here.
        return result;
    }
}

Or should I check first, cast later?

public string Describe(ICola cola)
{
    if (cola is CocaCola)
    {
        coke = (CocaCola) cola;
        string result;
        // some unique coca-cola only code here.
        return result;
    }
    if (cola is Pepsi)
    {
        pepsi = (Pepsi) cola;
        string result;
        // some unique pepsi only code here.
        return result;
    }
}

Can you see any other way to do this?

© Stack Overflow or respective owner

Related posts about best-practices

Related posts about c#