Possible Duplicate:
Direct casting vs 'as' operator?
Can any one tell the actual difference between snippet of code?
var unknown = (object)new List<string>();
// Snippet 1: as operator
foreach (var item in unknown as IList<int>) {
// Do something with item
}
// Snippet 2: cast operator
foreach (var item in (IList<int>)unknown) {
// Do something with item
}
as operator would not raise an error but cast will raise an error of
InvalidCastExceptionFrom MSDN
The as operator is like a cast except that it yields null on conversion failure instead of raising an exception.
expression as typeis equivalent to:
expression is type ? (type)expression : (type)nullexcept that expression is evaluated only once.
Note that the as operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed using cast expressions.