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

Why do we use static class in c#?

497


What is a generic in c#?

509


What is a verbatim string literal and why do we use it?

480


Is string immutable in c#?

576


Is c# or c++ better for games?

468






What is the main usage of keyword “virtual” ? How does it work for a method or property?

520


What is difference between int and int in c#?

453


What are the 3 types of comments in c#?

523


What is difference between constants and readonly in c#?

488


What is a concrete class in c#?

534


What are actions in c#?

486


Suppose you have already existing application with Visual Studio 6 (VB 6, InterDev 6) and this application utilizes Windows 2000 COM+ transaction services. With this example how can you approach migrating this application to .NET?

510


What is null character in string?

526


How is the syntax written to inherit from a class in C#?Give an example ?

543


Does a class need a constructor c#?

489