Room of a pleinolijf

Ask yourself this: how do I want to be remembered ?

Type Casting Performance in .NET

Leave a comment

[ as taken from MSDN © Microsoft Corporation. All rights reserved. ]

The DirectCast keyword introduces a type conversion operation. You use it the same way you use the CType keyword, as the following example shows:

Dim Q As Object = 2.37		' Requires Option Strict to be Off.
Dim I As Integer = CType(Q, Integer)	' Succeeds.
Dim J As Integer = DirectCast(Q, Integer)	' Fails.

Both keywords take an expression to be converted as the first argument, and the type to convert it to as the second argument. Both conversions fail if there is no conversion defined between the data type of the expression and the data type specified as the second argument.

The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type, whereas DirectCast requires the run-time type of an object variable to be the same as the specified type.

In the preceding example, the run-time type of Q is Double. CType succeeds because Double can be converted to Integer, but DirectCast fails because the run-time type of Q is not already Integer. DirectCast throws an InvalidCastException error if the argument types do not match.

If the specified type and the run-time type of the expression are the same, however, the run-time performance of DirectCast is better than that of CType.

TechnoratiTechnorati Tags: , , ,


Author: pleinolijf

father | volleyballer | software engineer

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s