Winston Posted January 15, 2004 Posted January 15, 2004 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. Quote
Administrators PlausiblyDamp Posted January 15, 2004 Administrators Posted January 15, 2004 http://www.xtremedotnettalk.com/showthread.php?s=&threadid=73095&highlight=ctype+directcast http://www.xtremedotnettalk.com/showthread.php?s=&threadid=70566&highlight=ctype+directcast http://www.xtremedotnettalk.com/showthread.php?s=&threadid=80277&highlight=ctype+directcast Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Winston Posted January 15, 2004 Author Posted January 15, 2004 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. Quote
Administrators PlausiblyDamp Posted January 15, 2004 Administrators Posted January 15, 2004 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. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.