Casting, Why and what's the difference between them two

Winston

Well-known member
Joined
Jan 25, 2003
Messages
266
Location
Sydney, Australia
Hi guys im really not understanding whats the need of doing casting, whats the point of it :S i dont get it, and whats the difference between CType and Direct casting, and what happens if you dont do any casting.
 
Im stilla little confused as to why its necessary to do casting

like this code i found

Dim wr As HttpWebRequest = CType(WebRequest.Create("Http://"), HttpWebRequest)


Why are you converting it to HttpWebRequest when initially it was defined as HttpWebRequest already.
 
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vblr7/html/vakeydirectcast.asp

WebRequest.Create() actually returns a System.Net.WebRequest not HttpWebRequest - CType is forcing the conversion to the correct object type.

By default this is not required in VB as it will attempt conversions for you - this however can cause subtle bugs to creep in. If you follow the good practice of always using Option Strict On in your code these automatic conversions will fail, you have to tell the system what you want it to do. A bit more work but far more reliable code.

the example code you presented is not a good example of casting though:
DirectCast will only do conversions between them if they are of a compatible run-time type (either a common interface or part of the same inheritance heirachy).
CType will convert if any supported conversion exists.

In the example you provided HttpWebRequest is a sub class of WebRequest and as such DirectCast would have been a better choice.

Code:
Dim wr As HttpWebRequest = DirectCast(WebRequest.Create("Http://"), HttpWebRequest)
In practice I tend to avoid CType for a couple of reasons DirectCast is faster than CType and can be a lot safer when the above mentioned conditions are met.
Using a type specific conversion (Integer.Parse, Long.ToString, Convert.ToInt32 etc) is again safer and faster than the more generalised CType.
 
Back
Top