C# Corner
Tech
News
Videos
Forums
Trainings
Books
Events
More
Interviews
Jobs
Live
Learn
Career
Members
Blogs
Challenges
Certifications
Bounties
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
.NET
ADO.NET
Android
ASP.NET
C#
Databases & DBA
Design Patterns & Practices
Java
Learn iOS Programming
OOP/OOD
SharePoint
Software Testing
Web Development
WPF
View All
1
Reply
Direct CAST vs CType ?
Marcus
14y
14.6k
0
Reply
Delete Row
Delete Column
Insert Link
×
Insert
Cancel
Embed YouTube Video
×
Width (%)
Height (%)
Insert
Cancel
Table Options
×
Rows
Columns
First row as header
Create Table
Insert Image
×
Selected file:
Alignment
Left
Center
Right
Select an image from your device to upload
Upload to Server
Cancel
Submit
1) CType is capable of a *cast* or a *conversion*. DirectCast can only
*cast*
By "conversion" I mean converting one datatype to another (e.g. string to
integer, decimal to integer, object to string etc).
By "cast" I mean changing one type of object into another type that is
related to it by one of the following rules:
a) The type you're converting the object to must be the same type
e.g.
--------------
Dim a as String = "hello"
Dim b as Object = a
Dim c as string = directcast(b, String)
--------------
Variable b is an object that holds a string, so you can cast it to a string.
b) If converting to an interface, the type you're converting must implement
the interface
e.g.
---------------------
Dim a as New MyInterfaceObejct
Dim b as IInterface = directcast(a, IInterface)
----------------------
c) If converting to a derived type, the runtime type of the object must be
the derived type or one of it's own derived types :S
e.g.
----------------------
Dim a as Base = New Derived
Dim b as Derived = directcast(a, Derived)
----------------------
2) Use directcast whenever a "type relationship" exists - it is slightly
faster (in some cases anyway), but forces you to be more aware of
conversions that are going on.
3) Use Ctype when a type relationship doesn't exist, but a value
relationship does (e.g. converting the string "123" to the integer 123)
Vinoth Arunraj
13y
0
What do you mean by virtual function and virtual classes?
ReadOnly vs Const?
Message