How should I cast in VB.NET?

.net, casting, vb.net

Solution

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.

Problem

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)

Original source

Related problems