What are the differences between the following casts and when to use each one?

4
  

Casting
  [...] process where one type of object is explicitly converted to another type, if conversion is allowed.
Source: > Stack overflow in Portuguese

Assuming the following situation:

var i = 10

What are the differences between the casts below and when should I use each? I would also like to know about their performance, if there is a difference.

  • i.ToString()
  • DirectCast(i, String)
  • CType(i, String)
  • CStr(i, String)
  • TryCast(i, String)
  • asked by anonymous 09.09.2016 / 00:51

    1 answer

    6
    • i.ToString() results in the textual representation of the object , is not necessarily a conversion as many think. It works for anything. There is more in Convert.ToString () and .ToString () .
    • DirectCast(i, String) is another cast operator when you do not know which is the type that will be converted and there are no guarantees it will work, throwing an exception if there are problems. It is the equivalent of (string)i of C #, or almost, they do not have exactly the same semantics.
    • CType(i, String) is a unique conversion form of VB.Net, it does not work in C #. The operator must be implemented in the type used. I see that it is not usually recommended (there are those who prefer CStr , there are those who prefer DirectCast , although the official recommendation is to prefer it. Mine is not to use VB.Net: P
    • CStr(i) is the cast operator specific to string of VB.Net (exclusive). It is a data converter. It has a better performance for some compiler optimization.
    • TryCast is the cast operator that does not result in an error , if the conversion fails the null will be returned ( null in C # and Nothing in VB.Net). Equals i as string of C #. Understand What's the difference between an explicit cast and the as operator?

    I've consulted some sources since VB.Net is not my specialty. And I've seen that there's a lot of controversy on the subject and neither official documentation nor people writing about it seem to adequately explain the differences between them. Even if someone post here something theoretically conclusive, if it is not very well founded, I will distrust.

    Note that there is no point in looking for performance if the engine does not do what you want. There you will be comparing oranges with bananas. In this example DirectCast does not work, it is not possible to transform an integer into text in this way. And the TryCast would result in null.

    Depending on what you want, neither is suitable. When you get external data that you do not have control of, all of these are problematic.

    The performance also depends on the data source. Converting string to string is very fast. Getting the textual representation may be faster in that conversion. So it's hard to say which one is faster.

    In this example, it seems that CStr is the fastest.

        
    09.09.2016 / 01:46