5

Is there any time CType() is the proper option over other methods? I did plenty of thinking on this myself, but wanted to put the question in hopes there would be answer to my question so I can put the question to rest in my workplace.

My idea is that CType() should never be used. But others seem to think it's still around for something other than backward-compatibility. So is there still a use for it?

A big problem is that many people don't seem to understand the difference between Casting and Converting.

Converting Vs Casting

This was one such line of code:

With objZipFile.GetEnumerator()
    While .MoveNext
        objZipEntry = CType(.Current, ZipEntry)
        … all this work is done with the objZipEntry
    End While
End With

If my buddy ever reads this, he'll be like, "MY CODE!!!!" lol. Yes, this is your code. And as I discussed with him, .Current is an enumeration of objZipFile, but its type is ZipEntry. So why is he "Converting" with CType(), when what he's really doing here is Casting. He should be using DirectCast(.Current, ZipEntry).

So the proper way to Cast something is to use DirectCast(). But this isn't a discussion about DirectCast(). The point here is that CType() Should certainly not be used to Cast, it's a Conversion tool, so let's talk more about Converting.

To CType() or Not To CType(), I don't think so

In the simplistic example, I have a string "123", and I want the string to be converted to an Integer. So many times, you see something like this:

Dim result as Integer = 0
result = CType("123", Integer)

Great! It Works! Then what is the difference between that and this:

Dim result as Integer = 0
result = Integer.Parse("123")

Well, with that exact example, the difference is that CType() took more resources to run. If I gave you two clear drinks and told you one had a health rating of 10, and the other of 9. You don't choose the 9 on principle that it isn't that much less healthy, you choose the dam 10. Also, the Integer.Parse line is a couple characters of less typing.

Okay, but what if your input isn't "123"? What if the input is "UrMom"? I hear CType() won't break... but as far as I know, that isn't true. CType() breaks just as much as Type.Parse(). I'd like some arguments on that. Though an argument supporting CType()'s resilience alone isn't reason enough to use CType().

On the other hand, we have this option in the Type-Class:

Dim MyInt As Integer = 0
Dim TryInt As Integer = 0
If Integer.TryParse("54", TryInt) Then
    MyInt = TryInt 
Else
    'Handle it appropriately 
End If

Not only are we parsing the data, but if it doesn't parse, we are handling it correctly. Which is a much better option that throwing a Try/Catch around bad code and letting it break before handling its failure in the Catch/Finally.

Keep in mind, there may be multiple different ways to cast and convert, but the main purpose of this question is to prove or disprove that CType() simply shouldn't be used.

My main argument is this... The only arguments I've seen that support the use of CType() are those that say CType() won't break if passed bad data, or that CType() is better if you are unsure of the data going in. In response to that I say Pish-Posh. Rethink your code, place conditionals, and know what you're wanting to use the item for. If something happens that you weren't expecting, handle it correctly.

So is there any time CType() is the proper option over other methods? Please provide examples.

  • Assuming you're being light and sarcastic: Lol, thanks Jeff. In case you aren't... If nothing else mattered (which a lot more does), I'd obviously choose 2 less characters than otherwise. – Suamere Sep 10 '13 at 1:49
  • Thanks for the clarification in your edit, but you should review this: programmers.stackexchange.com/help/editing – Robert Harvey Sep 10 '13 at 15:38
  • Microsoft originally suggested DirectCast was a back-end construct that you don't need to know about -- just use CType. But everyone who understood the difference used DirectCast when casting. The point about CType is that it can try both conversion and casting, if required. So when you really don't know what could be in an Object you might just use CType to allow the best possible chance of getting valid data rather than an exception. – Mark Hurd Sep 14 '13 at 11:18
  • @MarkHurd That is a huge proponent response for CType, so I'm glad you brought it up. A co-worker made this same argument. I ended up refactoring his "unknown items" into a set of classes following an interface and used dependency injection. I can't think of a time that you might have a Conversion Or Casting, and not know which. That has to be some messy stuff. I'd love to see a legit SOLID OO example of that, seriously. – Suamere Sep 16 '13 at 17:56
  • 3
    How is my question not clear? CType Is a method with similar use to Parsing Methods and less similar to Casting Methods. I asked, "Is there any time CType() is the proper option over other methods? Please provide examples." I need fellow engineers to give examples when CType is preferred over other options for readability, maintainability, performance, or other objective reasons. I don't care if nobody can answer my question, or if the answer is just "Never" but it certainly shouldn't be closed or on-hold. This relates to programming practices, not coding, and seems perfectly legitimate. – Suamere Sep 20 '13 at 4:39
1

CType is often useful when dealing with legacy code and database records -- where the "correct" field can potentially be of more than one type. For instance a date or a date string. Refacoring this can be time consuming and error prone, particularly when the results are from stored procedures and are also used by reports.

  • jmoreno! Familiar face. Is it not true that; Even if you have no clue what an incoming type is, you do know what you plan to do with it. In this example, you plan to use it as a Date, and that's all that matters. Other than changing CType(object, Date) to Date.Parse(object), you may need to check if you're catching CType-Specific exceptions, which would be awkward because that means you're expecting failures and would be better off with Date.TryParse() anyway. – Suamere Sep 21 '13 at 13:58
  • Also... I believe there's an article somewhere that says Ctype("3:45", Date) properly parses 3:45, whereas Date.Parse("3:45") also adds the current date. I'd say that breaks explicit development. If you convert a string to a Date, it should be a Date. If you want to parse a TimeSpan, you should use TimeSpan.Parse("3:45"). In this sense, CType is doing something unintuitive. – Suamere Sep 21 '13 at 13:59
  • Lastly, lol... sorry I type a lot. I do think that just because CType exists in Legacy code, doesn't merit re-factoring or changing it. Unless it is used millions of times across multiple projects daily, it won't be causing enough slowdown to merit refactor. But in future projects, it would be discouraged unless an answer comes up with a good reason otherwise, which I sorta hope happens. – Suamere Sep 21 '13 at 14:00
  • @Suamere: there is no Date.Parse(object). And I have seen differences between what the various type conversions output when dealing with dates-- I wouldn't change from one to the other unless I fully understood what was being passed and what was being returned. – jmoreno Sep 21 '13 at 16:40
  • Well put. I would have added .ToString. And while most of the question involves choosing CType over other options (such as in future development)... I would actually be happy to see an example in legacy code where keeping CType over changing to a different option is the best choice. I'm guessing that once a coder "fully understand[s] what's being passed and what [is] being returned", though, it would become clear that CType isn't the best option. Again, I'd love to find an example. – Suamere Sep 21 '13 at 19:44
-3

Edit: This question/answer pair were during a C++/C# developer's short stint in the confusing world of Visual Basic. It turns out that the proper answer is: Don't use Visual Basic. At this time, the best support for CType() is a VB6 to early .NET support document from 2003. EndEdit

After allowing this question to live online for a while, and also working with peers on research and usage regarding Casting and Converting, the answer has become clear.

The question was: Is there any time CType() is the proper option over other methods?

The answer is: No. From this point on, never use CType().

The only argument is: "What if you don't know the type you're casting?"

The counter argment to that is: Then refactor your program, be more explicit with your intentions, and perhaps stop using weak-typed objects, "strong-typed" datasets, or datasets in general.

  • 1
    -1 "From this point on, never use CType()." There is always an exception to every rule. Metaprogramming and other edge cases often dictate that while there are best practices, there are always places where obscure, poor performance functions are necessary. – Ampt Jun 30 '14 at 20:53
  • Although I will say good job on the diligence to the question :) – Ampt Jun 30 '14 at 21:00
  • So undo the -1 and create an answer to the question. I literally put CType() in the same realm as GoTo (for C#/VB). Some devs might say there's always an exception to the rule, but if I see GoTo in code in any business I work with, I'd rip the developer a new one. Same now with CType() when .Net has alternatives that are less resource intensive and more explicit for intention. Also, I did say "From this point on", meaning nobody expects legacy junk code to be completely refactored if you have the issue of bad data typing or something. – Suamere Jul 1 '14 at 13:38
  • Actually the recommendation from Microsoft is exactly the opposite: msdn.microsoft.com/en-us/library/Aa289509 See Conversion Functions, CType, DirectCast, and System.Convert Section – Matt Wilko Aug 11 '15 at 14:21
  • @Ampt: If metaprogramming is an "edge case", you're doing it wrong. :P – Mason Wheeler Aug 17 '15 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.