Jump to content
Xtreme .Net Talk

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


Recommended Posts

Posted
Hi guys i'm really not understanding what's the need of doing casting, what's the point of it :S i don't get it, and what's the difference between CType and Direct casting, and what happens if you don't do any casting.
  • Administrators
Posted

I'm stilla little confused as to why it's 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.

  • Administrators
Posted

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.

 

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.

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...