I want to know what exactly are the differences between CStr(), Str() and .ToString()?
Label1.Text = CStr(Int(Rnd() * 10))
and
Label1.Text = Str(Int(Rnd() * 10))
and
Label1.Text = Int(Rnd() * 10).ToString
If I use this condition:
If Label1.Text = "7" Then
'Some code here
End If
Str() doesn’t work here. What’s the difference?
ToString will call the
.ToString()function on a particular instance.In practice, this means that it will throw an exception if the object in
question is
Nothing. However, you can implement.ToString()in your ownclasses to get a useful string representation of your object, whereas
CType/CStronly work with built-in classes and interfaces.CStr and CType(expression, String) are exactly equivalent (I’m not
sure where the other poster got the idea that
CStris faster). But theyaren’t really functions, they’re compiler directives that will emit very
different code depending on the declaration of expression. In most
cases, these directives call a bunch of internal VB code that tries to
get a reasonable string out of expression.
DirectCast(expression, String) assumes that the expression in
question really is a
Stringand just casts it. It’s the fastest of allthese options, but will throw an exception if expression is anything
other than a
String.