Possible Duplicate:
Casting vs using the ‘as’ keyword in the CLR
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)
{
var coke = (CocaCola) cola;
string result;
// some unique coca-cola only code here.
return result;
}
if (cola is Pepsi)
{
var pepsi = (Pepsi) cola;
string result;
// some unique pepsi only code here.
return result;
}
}
Can you see any other way to do this?
If the object may or may not be of the type you want then the
asoperator (your first method) is better in two ways:iskeyword, the C# compiler internally translates it toas, ie.coke is Colais equivalent to(coke as Cola) != null)If the object should always be of the requested type then just do
(Coke)colaand let it throw an exception if that’s not the case.