473,807 Members | 2,827 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

CStr() vs. .ToString()

Book I am reading says that Cstr() is best method for efficency and safety
however it doesnt compare that method of the .ToString() method.

Which is best.

Thanks
Feb 18 '06
101 19260
"Scott M." <s-***@nospam.nosp am> schrieb:
both points of view are valid, however i use the vb string methods as the
compiler makes optimzations that can improve performance over the native
.Net
methods, also i find the vb methods read better.
The VB 6.0 way are not methods, they are functions. The .NET way are
object methods. The VB.NET compiler does NOT optimize the VB 6.0
functions to work BETTER than the natvie .NET object methods.


Does this really matter? The JIT compiler could inline the type conversion
functions.
To answer your question, ToString would be my suggestion, rather than
CStr(). ToString is a method of the Object Type, and since all classes
inherit from Object, all objects have this method.


'ToString' and 'CStr' serve different purposes. 'ToString' won't work on
'Nothing' references, which is a downside /if/ a 'Nothing' reference should
be converted to an empty string. That's exactly where 'CStr' can be used.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Feb 19 '06 #21
Thanks CMM, what you wrote is what I thought was true and I was looking for a
comfirmation.

As far as Scott goes I was refering to a "method" using the meaning of the
word "a way to". For my purposes it couldnt matter less if its a function or
a method.
"CMM" wrote:
I don't think that's true at all. First off, CStr,CBool, Etc. are all just
easier-to-read specialized wrappers around CType..... which in and of itself
is a special "VB" construct. The true "non-VB" casting operator is
DirectCast(...) .

Contrary to what Scott M says you're SUPPOSED to use them. What's the point
of using VB if you're not going to use its special methods that make your
life easier? This is straight from the VB documentation:

"As a rule, you should use the Visual Basic type conversion functions in
preference to the .NET Framework methods such as ToString(), either on the
Convert class or on an individual type structure or class. The Visual Basic
functions are designed for optimal interaction with Visual Basic code, and
they also make your source code shorter and easier to read. In addition, the
..NET Framework conversion methods do not always produce the same results as
the Visual Basic functions, for example when converting Boolean to Integer.
For more information, see Troubleshooting Data Types."

In addition, although I'm a guy who always initializes strings and objects
as soon as possible rather than have them sit around until my algorithm uses
them- so I don't really care about the following- but, there's an advantage
to using VB's functions: they interpret "Nothing." You can't use the OO
methods on a string that is "Nothing" (s.ToUpper for instance won't work).

--
-C. Moya
www.cmoya.com
"Scott M." <s-***@nospam.nosp am> wrote in message
news:O7******** ******@TK2MSFTN GP14.phx.gbl...
IMHO (and this has been debated for quite some time now), you should view
all of the old "data-type" specific functions as legacy functions and no
longer use them. Instead, use the more object-oriented methods of a type.

CStr, CBool, CDbl, CInt, etc. would all be replaced with CType or
.ToString
All date/time functions would be replaced with methods and properties of
the Date class
All string functions would be replaced with methods and properties of the
String class.

et all.
"Sean" <Se**@discussio ns.microsoft.co m> wrote in message
news:68******** *************** ***********@mic rosoft.com...
Book I am reading says that Cstr() is best method for efficency and
safety
however it doesnt compare that method of the .ToString() method.

Which is best.

Thanks



Feb 19 '06 #22
>> The VB 6.0 way are not methods, they are functions. The .NET way are
object methods. The VB.NET compiler does NOT optimize the VB 6.0
functions to work BETTER than the natvie .NET object methods.
Does this really matter? The JIT compiler could inline the type
conversion functions.


I was merely pointing out the inacurracy of the previous post. I'll leave
it up to the reader to determine if they care about the details.
To answer your question, ToString would be my suggestion, rather than
CStr(). ToString is a method of the Object Type, and since all classes
inherit from Object, all objects have this method.
'ToString' and 'CStr' serve different purposes. 'ToString' won't work on
'Nothing' references, which is a downside /if/ a 'Nothing' reference
should be converted to an empty string. That's exactly where 'CStr' can
be used.


As stated by others already, good programming practice would dictate that
data should be validated before being converted. So, I suppose I could say,
"Does it really matter since any good programmer would be checking for
nothing before converting the data?".

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Feb 19 '06 #23
Same answer as when you asked the same question earilier in the thread.
"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
"Bob Lehmann" <no****@dontbot herme.zzz> schrieb:
You can't use the OO methods on a string that is "Nothing"


Why would you want to?

Oh, I get it, you're too lazy to check the data before performing an
operation it. Isn't checking your data a 100 level concept?


Why type 'If s IsNot Nothing AndAlso s.Length > 0 Then' if you could
shorten it to 'If Len(s) > 0 Then'? The same applies to 'ToString' vs.
'CStr': Why type

\\\
If o Is Nothing Then
s = ""
Else
s = o.ToString()
End If
///

if you could archieve the same by using

\\\
s = CStr(o)
///

?

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Feb 19 '06 #24
Because CStr() wouldn't throw an exception if it encountered a Nothing
value, which could cause unexpected bugs in the application. ToString would
throw an exception and thus make it easier to determine the problem.
"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:uY******** *****@TK2MSFTNG P15.phx.gbl...
"Bob Lehmann" <no****@dontbot herme.zzz> schrieb:
At least you have a sound rationale -
"Checking if a variable actually contains data before doing a convert to
upper case is simply too much code."

Waaaaa! But Mom, those extra 20 keystrokes to check the data are soooo
hard
to do. And besides, my code is better readable since you know I don't
indent
If blocks.


Well, why duplicate this checking code all over the source code if it is
possible to encapsulate it cleanly in high-level wrappers/functions like
'CStr'?

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Feb 19 '06 #25
To add to this, you can't use DirectCast on anything but Reference Types
anyway, so CType will need to be used for all numeric casting anyway.
"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:%2******** *******@tk2msft ngp13.phx.gbl.. .
"CMM" <cm*@nospam.com > schrieb:
I don't think that's true at all. First off, CStr,CBool, Etc. are all just
easier-to-read specialized wrappers around CType..... which in and of
itself is a special "VB" construct.


ACK. While it doesn't matter if you use 'C<Type>' or 'CType(...,
<Type>)', I strongly recommend to use them instead of 'Convert.To*'.
The true "non-VB" casting operator is DirectCast(...) .


... which doesn't mean that 'DirectCast' should not be used. Personally I
prefer 'CType' for value types (type conversions) and 'DirectCast' for
type casts (reference types). However, some other people prefer to use
'CType' instead of 'DirectCast'.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Feb 19 '06 #26
Then you should absolutely go with your preference, which is what I said in
the first place. I merely indicated what my preference was and why.

Good luck!
"Sean" <Se**@discussio ns.microsoft.co m> wrote in message
news:BD******** *************** ***********@mic rosoft.com...
Thanks CMM, what you wrote is what I thought was true and I was looking
for a
comfirmation.

As far as Scott goes I was refering to a "method" using the meaning of the
word "a way to". For my purposes it couldnt matter less if its a function
or
a method.
"CMM" wrote:
I don't think that's true at all. First off, CStr,CBool, Etc. are all
just
easier-to-read specialized wrappers around CType..... which in and of
itself
is a special "VB" construct. The true "non-VB" casting operator is
DirectCast(...) .

Contrary to what Scott M says you're SUPPOSED to use them. What's the
point
of using VB if you're not going to use its special methods that make your
life easier? This is straight from the VB documentation:

"As a rule, you should use the Visual Basic type conversion functions in
preference to the .NET Framework methods such as ToString(), either on
the
Convert class or on an individual type structure or class. The Visual
Basic
functions are designed for optimal interaction with Visual Basic code,
and
they also make your source code shorter and easier to read. In addition,
the
..NET Framework conversion methods do not always produce the same results
as
the Visual Basic functions, for example when converting Boolean to
Integer.
For more information, see Troubleshooting Data Types."

In addition, although I'm a guy who always initializes strings and
objects
as soon as possible rather than have them sit around until my algorithm
uses
them- so I don't really care about the following- but, there's an
advantage
to using VB's functions: they interpret "Nothing." You can't use the OO
methods on a string that is "Nothing" (s.ToUpper for instance won't
work).

--
-C. Moya
www.cmoya.com
"Scott M." <s-***@nospam.nosp am> wrote in message
news:O7******** ******@TK2MSFTN GP14.phx.gbl...
> IMHO (and this has been debated for quite some time now), you should
> view
> all of the old "data-type" specific functions as legacy functions and
> no
> longer use them. Instead, use the more object-oriented methods of a
> type.
>
> CStr, CBool, CDbl, CInt, etc. would all be replaced with CType or
> .ToString
> All date/time functions would be replaced with methods and properties
> of
> the Date class
> All string functions would be replaced with methods and properties of
> the
> String class.
>
> et all.
>
>
> "Sean" <Se**@discussio ns.microsoft.co m> wrote in message
> news:68******** *************** ***********@mic rosoft.com...
>> Book I am reading says that Cstr() is best method for efficency and
>> safety
>> however it doesnt compare that method of the .ToString() method.
>>
>> Which is best.
>>
>> Thanks
>>
>>
>
>


Feb 19 '06 #27
"Scott M." <s-***@nospam.nosp am> schrieb:
Because CStr() wouldn't throw an exception if it encountered a Nothing
value, which could cause unexpected bugs in the application. ToString
would throw an exception and thus make it easier to determine the problem.


Well, but there are cases where I'd call 'CStr' intentionally because I want
a 'Nothing' reference to be converted to an empty string!

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Feb 19 '06 #28
I hear what you are saying, but as I said in the previous post, using CStr()
wouldn't allow you to discriminate between those Nothing values that you
intended to run across and Nothing values that inadvertantly may happen. As
others have said, a simple If statement that checks for the Nothing value
would allow you to get a Nothing value and convert it to an empty string
while still maintaining the integrety of the code.
"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:uu******** *****@tk2msftng p13.phx.gbl...
"Scott M." <s-***@nospam.nosp am> schrieb:
Because CStr() wouldn't throw an exception if it encountered a Nothing
value, which could cause unexpected bugs in the application. ToString
would throw an exception and thus make it easier to determine the
problem.


Well, but there are cases where I'd call 'CStr' intentionally because I
want a 'Nothing' reference to be converted to an empty string!

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Feb 19 '06 #29
"Scott M." <s-***@nospam.nosp am> schrieb:
I hear what you are saying, but as I said in the previous post, using
CStr() wouldn't allow you to discriminate between those Nothing values that
you intended to run across and Nothing values that inadvertantly may
happen. As others have said, a simple If statement that checks for the
Nothing value would allow you to get a Nothing value and convert it to an
empty string while still maintaining the integrety of the code.


'CStr' is different from 'ToString'. It's obvious that it doesn't behave
like 'ToString', and the additional behavior is publically well-known. So
using 'CStr' *iff* it makes sense does not break the integrity of the code.
It's the developer's fault if it breaks integrity.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Feb 19 '06 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
7710
by: Bill L. | last post by:
We recently noticed that the vb.net CStr function yields different results than the vb6 version when converting SQL decimal data. If, for example, the data is defined in SQL as decimal(19,10), the vb.net CStr function will return ten digits to the right of the decimal, regardless of the data value. In this case, if the data value is 5, the vb.net CStr function will return 5.0000000000. The vb6 CStr function will simply return 5. In other...
5
10476
by: c_shah | last post by:
Very beginner question.. What's difference between cstr vs .ToString vs Ctype for converting to String?
7
2770
by: John | last post by:
Hi I have a WinForm app with a bound form. When user enters a value in field rateid I lookup the respective rate amount from a table and assign it to field rate.I am using the DLookup function to achieve this (full code given below). This function returns a value of type object so I need to convert it to string. If I use the function as below (using ToString) it works fine; Me.txtRate.Text = DLookup(<parameters here>).ToString
0
9600
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10373
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10374
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7651
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5547
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5685
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4331
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3859
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3011
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.