Difference between using Cast and AS operator in following code?
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 InvalidCastException
From MSDN
The as operator is like a cast except that it yields null on conversion failure instead of raising an exception.
expression as type
is equivalent to:
expression is type ? (type)expression : (type)null
except 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.
Using the as operator differs from a cast in C# in three important ways:
It returns null when the variable you are trying to convert is not of the requested type or in it's inheritance chain, instead of throwing an exception.
It can only be applied to reference type variables converting to reference types.
Referenced Blog
链接地址: http://www.djcxy.com/p/73746.html