2

Possible Duplicate:
casting vs using the ‘as’ keyword in the CLR

Hi,

when to cast an object and when to use "as".

e.g:
class a= (class)object
and when to use
class a = object as class.

Community
  • 1
  • 1
Gaby
  • 2,923
  • 4
  • 36
  • 51
  • Duplicate of http://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword-in-the-clr - this article goes in depth to the various ways of casting. – Rob Levine Jul 29 '10 at 11:22
  • Yet another casting question. Please refer this - http://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword-in-the-clr – this. __curious_geek Jul 29 '10 at 11:24

3 Answers3

5

Using as is a safe option, as if the cast fails you do not get an exception, but the value returned is null.

If you want to get an exception when a cast is not possible, use ().

Oded
  • 477,625
  • 97
  • 867
  • 998
0
class a = object as class  

this is not raise an exception in case it cannot cast and it wokrs only for reference types

Arseny
  • 7,141
  • 4
  • 36
  • 52
0

This article seems to sum it up well...

http://gen5.info/q/2008/06/13/prefix-casting-versus-as-casting-in-c/

Peter O'Callaghan
  • 6,151
  • 3
  • 24
  • 27