|
-
May 3rd, 2008, 01:50 AM
#3
Re: Converting to string
 Originally Posted by Tom Sawyer
Everything in .NET inherits from System.Object, so everything in .NET has the ToString method available to it, therefore it should never fail on you except if the object isn't set to anything and it throws the null reference exception because you're trying to call a method of it.
Correct.
 Originally Posted by Tom Sawyer
CStr is a holdover from classic VB and, while it works in most cases, isn't really part of the .NET Framework and it isn't the best practice to use it instead of ToString.
Not true at all. CStr is no more a holdover from VB6 than any other VB.NET keyword. It is NOT a Runtime function (a member of the Microsoft.VisualBasic namespace) like MsgBox or Len. It is part of the VB.NET language itself, hence it turns blue in the code window. The truth of the matter is that CStr(obj) is simply a shorthand for CType(obj, String).
It is NOT best practice to use ToString in preference to CStr. CStr is more efficient than ToString because it is compiled inline rather than as a function call. If you want to cast a reference to a String object as type String then CStr is preferable to ToString. If you want to convert an object for which the CType operator is defined for type String then CStr is preferable to ToString. If you want to convert an object that is not a String, and for which the CType operator is not defined for type String, to a String representation then ToString is the only option.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|