Cast then check or check then cast?
- by jamesrom
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?