String conversion from an Object in VB.NET

  • Thread starter Thread starter Marlon
  • Start date Start date
M

Marlon

Which statement gives better performance (where obj can contain any of the
CLR runtime types)


1) CStr(obj)

or

2) obj.ToString()
 
They are essentially the same. CStr(obj) will generate a bit more IL code
than obj.ToString() because it is a call to a function that will turn around
and call ToString anyway.

If you are interested in performance, this article may help:
http://accessvbsql.advisor.com/doc/12798

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
 
Hi Marlon,

From a general view, I always think call obj(or other class's ) ToString
will be better if there is no particular requirement ot use any Convert
class to do the same task. And as for the CStr, this is a visualbasic
compatible expression which is actually translated to the following call at
runtime:

Microsoft.VisualBasic.CompilerServices.StringType.FromObject(Object value)
in microsoft.visualbasic.dll

And the StringType.FromObject will also do a switch list to compare the
object's Typecode and do the convertion. So I think directly use ToString()
method is always the preferred way.
Do you think so?

thanks.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
 
Back
Top