2

Possible Duplicate:
Casting: (NewType) vs. Object as NewType

Just wanted to know which one is faster and what's the difference.

MyClass test = someclass as MyClass;

or

MyClass test = (MyClass)someclass;

Community
  • 1
  • 1
kakopappa
  • 5,023
  • 5
  • 54
  • 73

4 Answers4

3

The difference is that the as keyword does not throw an exception when it fails and instead it fills the l-value with null whereas casting with brackets will throw an InvalidCastException.

Nobody
  • 4,731
  • 7
  • 36
  • 65
  • 1
    And it is much preferable to have a meaningful exception now than a NullReferenceException later. So I would say stick with a regular cast unless you handle the nulliness immediately after an 'as' cast. – Paul Ruane Aug 25 '10 at 16:03
  • 1
    Also note that you can't use the as keyword with value types. – Dr. Wily's Apprentice Aug 25 '10 at 16:06
1

The as keyword will return null if the desired cast is not valid. Explicit casting will throw an exception in that case. Consequently, I believe the implicit cast (as) is slower, though it's likely negligible.

TreDubZedd
  • 2,571
  • 1
  • 15
  • 20
1

Faster? It probably isn't going to ever matter. You'll have to wait until there is a scenario where your performance profiling application tells you to that the cast is taking too long.

Difference?

Will set test to null when someclass can't be cast to MyClass.

MyClass test = someclass as MyClass; 

Will throw an exception when someclass can't be cast to MyClass.

MyClass test = (MyClass)someclass;
John Fisher
  • 22,355
  • 2
  • 39
  • 64
0

as casting is faster than prefix casting, but doesn't produce reliable results, ie. it returns null if the cast can't be executed. You'll have to deal with that yourself. Prefix casting will throw an exception if T1 can't be casted to T2.

See: blog

as vs prefix

See codeproject

Femaref
  • 60,705
  • 7
  • 138
  • 176