0

Possible Duplicate:
Direct casting vs 'as' operator?

Firstly I am sorry if this is a duplicate, I have tried to google but it is not an easy "google to do"!

Is there a difference (functionally, performance wise, etc) between the following code fragments:

MyClass myClass = (MyClass)someObject;

MyClass myClass = someObject as MyClass;
Community
  • 1
  • 1
melodiouscode
  • 2,105
  • 1
  • 20
  • 41

2 Answers2

9

Yes there is a difference!

as operator will set variable to null if casting fails

Explicit casting will raise exception

opewix
  • 4,993
  • 1
  • 20
  • 42
1

Yes, the first variant will throw an exception, if it can't cast 'someObject' to 'MyClass'. Whereas the second will then just return null.

Franky
  • 651
  • 3
  • 11