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

Asked

Viewed 195 times

5

Casting
[...] process where an object type is explicitly converted to another type, if conversion is allowed.
Source: Stackoverflow in Portuguese


Assuming the following situation:

var i = 10

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

  1. i.ToString()
  2. DirectCast(i, String)
  3. CType(i, String)
  4. CStr(i, String)
  5. TryCast(i, String)

1 answer

8


  • i.ToString() results in the textual representation of the object, not necessarily a conversion as many think. It works for anything. Has more in detail on Convert.Tostring() and . Tostring().
  • DirectCast(i, String) is another operator of cast when it is not known which type will be converted and there are no guarantees that will work, making 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 form of conversion unique to VB.NET, does not work in C#. The operator needs to be implemented in the type used. I see that it is not customary to recommend it (some prefer the CStr, there are those who prefer the DirectCast, although the official recommendation is to prefer it. Mine is not to use VB.NET :P
  • CStr(i) is the operator of cast specific to string from VB.NET (exclusive). It is a data converter. It performs better by some compiler optimization.
  • TryCast is the operator of cast which does not result in error, if the conversion fails the null will be returned (null in C# and Nothing in VB.NET). Equivalent to i as string of C#. Understand What is the difference between an explicit cast and the operator?

I consulted some sources since VB.NET is not my specialty and I saw that there is much controversy on the subject and neither the official documentation nor people who write about it seem to adequately explain the differences between them. Even if someone posts something here theoretically conclusive, if it’s not well-founded, I’ll suspect.

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

Depending on what you want none of these is suitable. When you receive external data that has no control, all of these are problematic.

Performance also depends on the data source. Convert string for string is very fast. Getting the textual representation can be faster in that conversion. So it’s complicated to state which is faster.

In this example, everything indicates the CStr is the fastest.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.