0

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
}
Community
  • 1
  • 1
urz shah
  • 471
  • 2
  • 8
  • 18
  • As will return null if the cast fails; the explicit cast will throw an exception if it fails. – Tim Sep 29 '12 at 09:42
  • I have checked your link but there is much difference between two questions. – urz shah Sep 29 '12 at 09:44
  • @urzshah The differences are 1) you put it in a `foreach` loop, and 2) you're casting to an interface type. Neither of those differences is relevant to your question. –  Sep 29 '12 at 09:51

2 Answers2

2

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.

larsmoa
  • 12,604
  • 8
  • 62
  • 85
yogi
  • 19,175
  • 13
  • 62
  • 92
  • thnx.It is very clear from your answer that 1st code will throw null reference exception but second will throw Invalid cast exception which tell about actual problem.so always keep away from AS operator where user defined conversions are required. – urz shah Sep 29 '12 at 10:21
0

Using the as operator differs from a cast in C# in three important ways:

  1. 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.

  2. It can only be applied to reference type variables converting to reference types.

  3. Using as will not perform user-defined conversions, such as implicit or explicit conversion operators, which casting syntax will do.

Referenced Blog

Kundan Singh Chouhan
  • 13,952
  • 4
  • 27
  • 32