How should I cast in VB.NET?
Asked Answered
G

7

163

Are all of these equal? Under what circumstances should I choose each over the others?

  • var.ToString()

  • CStr(var)

  • CType(var, String)

  • DirectCast(var, String)


EDIT: Suggestion from NotMyself

  • TryCast(var, String)
Gunshy answered 2/9, 2008 at 21:49 Comment(0)
G
175

Those are all slightly different, and generally have an acceptable usage.

  • var.ToString() is going to give you the string representation of an object, regardless of what type it is. Use this if var is not a string already.
  • CStr(var) is the VB string cast operator. I'm not a VB guy, so I would suggest avoiding it, but it's not really going to hurt anything. I think it is basically the same as CType.
  • CType(var, String) will convert the given type into a string, using any provided conversion operators.
  • DirectCast(var, String) is used to up-cast an object into a string. If you know that an object variable is, in fact, a string, use this. This is the same as (string)var in C#.
  • TryCast (as mentioned by @NotMyself) is like DirectCast, but it will return Nothing if the variable can't be converted into a string, rather than throwing an exception. This is the same as var as string in C#. The TryCast page on MSDN has a good comparison, too.
Gotthard answered 2/9, 2008 at 22:3 Comment(7)
There is never a reason to use CType(var, String) instead of CStr(var), they do exactly the same thing.Internationalize
@Maslow TryCast only works for value types, since it needs to be a type that can have Nothing as a valueGotthard
@Martinho quite right. That should say "only works for reference type"Gotthard
CStr(var) will choke and raise an exception if the var is DBNull.Value, but the alternate Convert.ToString(var) will return an empty string.Gottschalk
Dim myList AS ArrayList=new ArrayList When you write (From e In myList select CType(e.Name,String)).ToArray() it doesn't work. I came to write ... select CType(e.Name.ToString,String)).ToArray() and I retrieved my smile.Unblessed
Unfortunately, VB's TryCast doesn't even work with nullables, opposed to C#'s as. For example myObject as double? is perfectly legal and returns null if cast fails, but TryCast(myObject, Double?) gives compiler error.Echevarria
DirectCast(var, String) is used to up-cast an object into a string. => this is a downcastThermochemistry
N
14

Cstr() is compiled inline for better performance.

CType allows for casts between types if a conversion operator is defined

ToString() Between base type and string throws an exception if conversion is not possible.

TryParse() From String to base typeif possible otherwise returns false

DirectCast used if the types are related via inheritance or share a common interface , will throw an exception if the cast is not possible, trycast will return nothing in this instance

Needlepoint answered 25/11, 2008 at 20:2 Comment(0)
M
9

MSDN seems to indicate that the Cxxx casts for specific types can improve performance in VB .NET because they are converted to inline code. For some reason, it also suggests DirectCast as opposed to CType in certain cases (the documentations states it's when there's an inheritance relationship; I believe this means the sanity of the cast is checked at compile time and optimizations can be applied whereas CType always uses the VB runtime.)

When I'm writing VB .NET code, what I use depends on what I'm doing. If it's prototype code I'm going to throw away, I use whatever I happen to type. If it's code I'm serious about, I try to use a Cxxx cast. If one doesn't exist, I use DirectCast if I have a reasonable belief that there's an inheritance relationship. If it's a situation where I have no idea if the cast should succeed (user input -> integers, for example), then I use TryCast so as to do something more friendly than toss an exception at the user.

One thing I can't shake is I tend to use ToString instead of CStr but supposedly Cstr is faster.

Manor answered 2/9, 2008 at 22:12 Comment(0)
C
8

I prefer the following syntax:

Dim number As Integer = 1
Dim str As String = String.TryCast(number)

If str IsNot Nothing Then

Hah you can tell I typically write code in C#. 8)

The reason I prefer TryCast is you do not have to mess with the overhead of casting exceptions. Your cast either succeeds or your variable is initialized to null and you deal with that accordingly.

Circus answered 2/9, 2008 at 21:54 Comment(3)
I think you're wrong. it's not a good idea to use TryCast at all. in a case like yours, number.ToString() or CStr(number) should be used.Chassis
@Shimmy: What's the reason behind not using TryCast at all? Isn't it better that DirectCast to avoid an exception in certain scenarios?Callender
@Callender and NotMyself. TryCast is only for REFERENCE types. Here, we have an Integer, which is a VALUE type. Compiler will reject TryCast. Also, the goal is a String. Any .Net entity except Nothing supports .ToString(). A value type, such as Integer, can't be Nothing. So in this case, either CStr(number) or number.ToString() is safe. In the general case (not just value types), CStr(whatever) is safe, because it can handle Nothing -- the result will be Nothing, in the String variable. TryCast is very useful -- just not here.Unweave
G
4

User Konrad Rudolph advocates for DirectCast() in Stack Overflow question "Hidden Features of VB.NET".

Gunshy answered 19/9, 2008 at 16:28 Comment(2)
-1 because DirectCast is blatantly NOT appropriate here, except under very limited situation, which you didn't bother to mention. DirectCast is good when you know you have two RELATED REFERENCE TYPES, and want an efficient casting between them. Since the question is about obtaining a String, it is unlikely that the OP was discussing a situation where DirectCast is appropriate.Unweave
... If the question hadn't mentioned String and ToString, my complaint would not apply. You shouldn't advocate for DirectCast, until you have narrowed the topic down from general CONVERSION.Unweave
S
1

According to the certification exam you should use Convert.ToXXX() whenever possible for simple conversions because it optimizes performance better than CXXX conversions.

Sinistrocular answered 16/3, 2011 at 18:44 Comment(1)
FYI, According to Paul Vick at Microsoft, the Cxxx operators were faster than the Convert.Toxxx functions, at least in 2004, because Cxxx compiles directly to IL, rather than calling a function. Though his rationale seems dubious, given the ability to JIT-optimize away function calls. panopticoncentral.net/2004/05/31/the-native-net-languageUnweave
S
0

At one time, I remember seeing the MSDN library state to use CStr() because it was faster. I do not know if this is true though.

Semination answered 5/9, 2008 at 19:3 Comment(1)
DirectCast is faster than CStr, but you can only use it when casting a string object into a string variable. It will fail if you try to convert any other object into a string.Internationalize

© 2022 - 2024 — McMap. All rights reserved.