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)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 ifvaris 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 asCType.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)varin C#.TryCast(as mentioned by @NotMyself) is likeDirectCast, but it will returnNothingif the variable can’t be converted into a string, rather than throwing an exception. This is the same asvar as stringin C#. TheTryCastpage on MSDN has a good comparison, too.