1

Possible Duplicate:
Direct casting vs 'as' operator?
Casting vs. using the as keyword in the CLR

In C#, whats the difference

var obj = (Array)Something

vs

var obj = Something as Array
Community
  • 1
  • 1
Jiew Meng
  • 84,767
  • 185
  • 495
  • 805
  • 3
    This is a dupe of many [questions](http://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword-in-the-clr) here. Is no one ever reading the documentation these days? – Dirk Vollmar Oct 05 '10 at 08:29
  • 1
    first hit when searching this site for `[c#] typecast` showed this: http://stackoverflow.com/questions/3724051/what-is-difference-between-normal-typecasting-and-using-as-keyword-closed which in turn is closed as a dup of other questions. Voting for closing – Isak Savo Oct 05 '10 at 08:33

3 Answers3

6

first will throw a CastException if invalid. The second will only result in obj = null instead.

danijels
  • 5,211
  • 4
  • 26
  • 36
1
var obj = (Array)Something 

will throw an InvalidCastExcpetion if Something not derived from System.Array or does not have a conversion operator for System.Array. This can be used with value types and reference types.

var obj = Something as Array

will return null (obj will be null) if Something not derived from System.Array or does not have a conversion operator for System.Array. This can be used only with reference types. You'd need to box you value type first.

bitbonk
  • 48,890
  • 37
  • 186
  • 278
1

As well as Danijels answers

The first can be used with any type.

The as operator can only be used on reference types.

Matt Ellen
  • 11,268
  • 4
  • 68
  • 90