What is the Difference between directcast and ctype?

Answer Posted / guest

Ans: 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. 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.
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.

Is This Answer Correct ?    4 Yes 4 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is the difference between the debug class and trace class? Documentation looks the same.

594


What are the properties of a string class?

590


What is an assembly qualified name

630


How to force my .net app to run as administrator on windows 7?

591


Why do we use stringbuilder in c#?

598






How many kinds of elements an array can have?

549


Why data types are important?

600


Are structs faster than classes?

619


Why is c# a good programming language?

550


Perfect Example Of While And Do-While Loop In C#.Net ?

640


How main method is called in c#?

594


What is use of hashtable in c#?

564


When should I throw an exception?

651


Explain how do I get deterministic finalization in c#?

572


Where are value types stored in c#?

597