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

Write a program to find the angle between the hours and minutes in a clock

0 Answers  


What is bit in c#?

0 Answers  


6. If we assign a value in textbox on Page_UnLoad event, will it display?

2 Answers   Mphasis,


What are the differences between value types and reference types?

0 Answers  


What is dao in c#?

0 Answers  


Explain the role of Garbage collector and its generations?

0 Answers   MCN Solutions,


What language is arduino?

0 Answers  


Are c# tuples immutable?

0 Answers  


To catch any possible exception What is the C# syntax written ?

0 Answers   Siebel,


Can you declare a C++ type destructor in C# like ~MyClass() ?

1 Answers  


How do you remove white spaces from a string?

0 Answers  


What is a method signature?

0 Answers  


Categories