What is the Difference between directcast and ctype?



What is the Difference between directcast and ctype? ..

Answer / 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

More C Sharp Interview Questions

Can you describe iuknown interface in short?

0 Answers  


What is the difference between dynamic type variables and object type variables in c#?

0 Answers  


What is use of private class in c#?

0 Answers  


What are generations and how are they used by the garbage collector?

0 Answers  


What is the difference between static and private constructor in c#?

0 Answers  






What is #region in c#?

0 Answers  


What is difference between events and delegates?

0 Answers  


Can interface inherit class in c#?

0 Answers  


Does C# supports multi-dimensional arrays ?

4 Answers   Microsoft,


What is use of hashtable in c#?

0 Answers  


what is object-oriented programming (oop) language?

0 Answers  


1)what is difference between char and varchar in sql server 2005 2) what is composite key and candidate key 3) what is temporary table and derived table 4) how to calculate difference between two dates

1 Answers   Wipro,


Categories