Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CStr() Str() .ToString()

Tags:

string

vb.net

I just want to know, what exactly the difference between the functions CStr() and Str() and also the .ToString()? With the code provided below, what's the difference between the three?

Label1.Text = CStr(Int(Rnd() * 10)) 

and

Label1.Text = Str(Int(Rnd() * 10)) 

and

Label1.Text = Int(Rnd() * 10).ToString 

When I used this condition

If Label1.Text = "7" Then      'Some code here End If 

...the Str() function didn't work here. What difference did it make? thanks in advance :))

like image 451
Aaron Avatar asked Jan 19 '12 10:01

Aaron


People also ask

What is CStr in VBA?

CSTR in VBA is a data type conversion function which is used to convert any value provided to this function to string, even if the given input is in integer or float value this function will convert the data type of the value to a string data type, so the return type of this function is a string.

What is Str in VB net?

In VB.NET, string is a sequential collection of characters that is called a text. The String keyword is used to create a string variable that stores the text value. The name of the string class is System.

What is CSTR in vbscript?

The CStr function converts an expression to type String.

What is str in Excel VBA?

The Microsoft Excel STR function returns a string representation of a number. The STR function is a built-in function in Excel that is categorized as a String/Text Function. It can be used as a VBA function (VBA) in Excel.


1 Answers

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 own classes to get a useful string representation of your object, whereas CType/CStr only 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 CStr is faster). But they aren'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 String and just casts it. It's the fastest of all these options, but will throw an exception if expression is anything other than a String.

like image 142
John Woo Avatar answered Nov 07 '22 21:11

John Woo