Click to See Complete Forum and Search --> : ToString() vs "as string"?
flamey
January 17th, 2008, 06:53 PM
I just notice in someone's code the were doing
string temp = objMO["..."] as string;
i've never seen this. is it any different from = objMO["..."].ToString(); ? Not by result in this case, but wondering what's the difference?
thnx
cjard
January 17th, 2008, 07:16 PM
objMO seems to be a HashTable, a container object that is indexed by a string. The string in this case is "..." and calling objMO["..."] will return the object associated with that key
There is no guarantee that that Object returned is of actual type string, so there IS a difference
suppose we said:
objMO["..."] = new System.Windows.Forms.Button();
Now we stored a instance of a Button to that key
if we try to cast the Button into a string with "as string" then it will fail and the result is null. If we call the Button's ToString() method, it is programmed to return a string of "System.Windows.Forms.Button" (i think)
Now, because ToString() on a string is overridden to return the string, there is no conceptual difference between "as string" and "ToString" if the object is a string. ToString will just perform a "return this" anyways.. So if you KNOW that hashtable is storing strings, there is no difference. If you KNOW it is NOT or you cannot be sure that it is not, then there MAY be a difference in the result
David Anton
January 17th, 2008, 07:52 PM
To clarify a bit: "as" in C# is just a cast which yields null (instead of an exception) when the cast attempt fails (VB also has this in the form of "TryCast").
jmcilhinney
January 18th, 2008, 12:22 AM
The two are intended for different purposes. The ToString method of any object is supposed to return a string representation of that object. Casting is quite different, and the 'as' key word performs a conditional cast, as has been said. The 'as' key word basically says "get me a reference of this type to that object if that object is this type" while ToString says "get me a string representation of that object". The result may be the same in some cases but the two should never be considered interchangeable because, as I said, they exist for different purposes. If your intention is to cast then you should always use a cast, NOT ToString.
flamey
January 18th, 2008, 09:35 AM
got it. thanks everyone!
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.