0

I just ran across another way to cast objects in C#. I have always used (CastType)variable. I just noticed some code using variable as CastType. The latter reminds me of VB.

Is there a difference between the two methods of casting other than syntax?

JabberwockyDecompiler
  • 3,318
  • 2
  • 42
  • 54

1 Answers1

6

The first one will throw InvalidCastException if the types don't match (refer to the documentation - "Explicit conversions" section). The second one (the as operator) will produce null value instead.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130