.toString() Ctype(), cstr(), DirectCast() ?? Which to use?

M

Michael Ramey

Hello,

There are quite a few ways to convert one object, say an integer to a
string.

Dim myStr as string
dim myInt as integer = 123

myStr = cstr(myInt)
myStr = myInt.toString()
myStr = CType(myInt, String)
or use DirectCast()

What is the preferred, fastest way? Any way I shouldn't be using because it
could be deprecated?

Thanks,
--Michael
 
T

Trev Hunter

DirectCast won't work for this example - it only works if the run time types
are the same e.g.

------------

Dim o as Object = "Hello"
Dim i as Object = Cint(5)
Dim s as string = directcast(o, String) ' Will work, because o is a string
at runtime
Dim s1 as String = directcast(1, String) ' Won't work

------------

As for the other ways, they are more or less the same. In the examples you
gave, if you follow the IL generated, they you'll notice that all end up
calling the Int32.ToString() method.

See the other posts in this group relating to this issue:

"CType() versus Convert.ToXXXX()"
"DirectCast vc CType"

HTH,

Trev.
 
A

AirPete

Michael said:
Hello,

There are quite a few ways to convert one object, say an integer to a
string.

Dim myStr as string
dim myInt as integer = 123

myStr = cstr(myInt)
myStr = myInt.toString()
myStr = CType(myInt, String)
or use DirectCast()

What is the preferred, fastest way? Any way I shouldn't be using
because it could be deprecated?

Thanks,
--Michael

They are are good ways of doing it, but I prefer ToString simply because I
feel it's the most readable.
Pick any of them you like best, and stick with it (for consistancy).

- Pete
 
A

AirPete

AirPete said:
They are are good ways of doing it, but I prefer ToString simply
because I feel it's the most readable.
Pick any of them you like best, and stick with it (for consistancy).

- Pete

Oops, I didn't see DirectCast, and as Trev noted, it only works if the types
are the same.

- pete
 
T

Trev Hunter

Oops, I didn't see DirectCast, and as
Trev noted, it only works if the types are the same.

Or if the types are related by inheritance or interfaces - i.e. a cast is
avaialble - not a conversion.

Trev.
 
C

Cor

Hi Michael.

For .toString you have only to push on the dot.

Why take another one?

Do not forget that in every program language a lot of things are for
backward compatibility.

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top