Simple question about strings

Posts   
 
    
Posts: 497
Joined: 08-Apr-2004
# Posted on: 29-Jun-2005 13:32:15   

Quick question for you all to take your mind off databases wink

If I have an "object" that I know to be a string, and I want to compare it to a string, is there any difference between:

if ( (string) myObject == "HELLO" )

and

if (myObject.ToString() == "HELLO")

I'm wondering about boxing, but I guess both operations are the same in this case....

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39801
Joined: 17-Aug-2003
# Posted on: 29-Jun-2005 13:46:06   

Boxing occurs when you store a value type in an object reference, and a string is not a value type wink

In your example, boxing doesn't occur. Though if you're not sure, simply do if(myObject.Equals("HELLO")) { //... }

that way, you're always safe. '==' is a hardcoded overloaded operator for strings, it normally does a reference (instance) compare. if myObject is a string, equals is overloaded in the string object and will do a value compare with whatever you pass in simple_smile

Frans Bouma | Lead developer LLBLGen Pro
Posts: 497
Joined: 08-Apr-2004
# Posted on: 30-Jun-2005 17:33:13   

Thanks for the info Frans wink

I don't know why, but I have a mental block when it comes to strings - I always think of them as value types which is so obviously not true flushed

Devildog74
User
Posts: 719
Joined: 04-Feb-2004
# Posted on: 07-Jul-2005 05:28:15   

MattWoberts wrote:

Thanks for the info Frans wink

I don't know why, but I have a mental block when it comes to strings - I always think of them as value types which is so obviously not true flushed

I beleive that in the VB6 days strings were value types, so that could be where youre getting hung up (if your an old vb 6 programmer)