472,985 Members | 2,625 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,985 software developers and data experts.

string comparison with ==

Hi

I am looking at some code which in many places performs string comparison
using == instead of Equals.

Am I right in assuming that this will in fact work "as expected" when it is
strings involved? By "as expected" I mean that as long as the strings are
instantiated using string literals, then == and Equals are the same.

string s1 = "xxx";
string s2 = "xxx";

if (s1 == s2)
{
}

if (s1.Equals(s2))
{
}

Peter
Nov 17 '05 #1
4 7125
Peter Kirk wrote:
Hi

I am looking at some code which in many places performs string comparison
using == instead of Equals.

Am I right in assuming that this will in fact work "as expected" when it is
strings involved? By "as expected" I mean that as long as the strings are
instantiated using string literals, then == and Equals are the same.

string s1 = "xxx";
string s2 = "xxx";

if (s1 == s2)
{
}

if (s1.Equals(s2))
{
}


Yes, they do the same thing. I believe the equal operator on string just
calls .Equals.
--
Tom Porterfield
Nov 17 '05 #2
Peter Kirk <pk@alpha-solutions.dk> wrote:
I am looking at some code which in many places performs string comparison
using == instead of Equals.

Am I right in assuming that this will in fact work "as expected" when it is
strings involved? By "as expected" I mean that as long as the strings are
instantiated using string literals, then == and Equals are the same.


It will work as expected whether or not they're string literals, so
long as both sides of the expression are strings (to the compiler) -
String overloads the == operator to call String.Equals(x,y).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #3
"Peter Kirk" <pk@alpha-solutions.dk> wrote in message
news:uB*************@TK2MSFTNGP15.phx.gbl...
Hi

I am looking at some code which in many places performs string comparison
using == instead of Equals.


To add to the other posts, here's some additional info from
what I've seen.

Example code :

private void button10_Click(object sender, System.EventArgs e)
{
string s1 = "hello"; // XXX
string s2 = string.Copy(s1);

if (s1 == s2)
MessageBox.Show("Test 1 : was equal");
else
MessageBox.Show("Test 1 : not equal");

object s1obj = s1;

if (s1obj == "hello") // YYY
MessageBox.Show("Test 2 : was equal");
else
MessageBox.Show("Test 2 : not equal");

if (s1obj == s2) // ZZZ
MessageBox.Show("Test 3 : was equal");
else
MessageBox.Show("Test 3 : not equal");
}
When run, this code displays :

"Test 1 : was equal"
"Test 2 : was equal"
"Test 3 : not equal"
The string class overloads the following "==" operator :

public static bool operator ==(string a, string b)
, so that when you use the "==" operator on two strings, the actual contents
of
the string are compared, and not their references. That is why test 1
passes.

In case of test 2, the overloaded "==" operator defined in the string class
is not invoked, because the s1obj variable is of type "object".
This results in a reference comparison. This is also what happens in test 3.

However, the results of test 2 and test 3 are different.
This is because in test 2, we got lucky, since the lteral constant : "hello"
on line marked "XXX" is the same (i.e. the same reference) as the literal
constant "hello" marked on line YYY. (I guess this is probably due to
dotnet realizing that the strings hold the same contents, so just make
them point to the one copy). (You could confirm this by evaluating
something like : object.ReferenceEquals(s1obj, "hello"), which
returns true.)
Even though test 2 worked, it is not really a good idea to use code
like this. (As shown by test 3).

The C# compiler even gives you a warning about lines YYY and ZZZ :

==

form1.cs(334,8): warning CS0252: Possible unintended reference
comparison; to get a value comparison, cast the left
hand side to type 'string'

==


Nov 17 '05 #4

Sorry, to clarify -:

using "==" when both sides are string variables, as in test 1,
is fine, but not a good idea (IMO) in cases such as test2 or test3.

"Stephen Ahn" <noaddress_at_noaddress.com> wrote in message
news:uZ**************@TK2MSFTNGP10.phx.gbl...

Even though test 2 worked, it is not really a good idea to use code
like this. (As shown by test 3).

Nov 17 '05 #5

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

Similar topics

10
by: David Graham | last post by:
Hi I have been busy going through the last weeks postings in an attempt to absorb javascript syntax (I guess it's not possible to just absorb this stuff in a passive way - I'm getting way out of...
2
by: Neil Zanella | last post by:
Hello, Consider the following program. There are two C style string stack variables and one C style string heap variable. The compiler may or may not optimize the space taken up by the two stack...
8
by: Grant Wagner | last post by:
I'm a bit confused by String() (typeof 'string') vs new String() (typeof 'object'). When you need to access a method or property of a -String-, what type is JavaScript expecting (or rather, what...
51
by: Alan | last post by:
hi all, I want to define a constant length string, say 4 then in a function at some time, I want to set the string to a constant value, say a below is my code but it fails what is the correct...
46
by: yadurajj | last post by:
Hello i am newbie trying to learn C..I need to know about string comparisons in C, without using a library function,...recently I was asked this in an interview..I can write a small program but I...
5
by: MaSTeR | last post by:
Can anyone provide a practical short example of why in C# I shouldn't compare two strings with == ? If I write this in JAVA String string1 = "Widget"; if (string1 == "Widget") ...
4
by: Jim Langston | last post by:
Is there any builtin lowercase std::string compare? Right now I'm doing this: if ( _stricmp( AmmoTypeText.c_str(), "GunBullet" ) == 0 ) AmmoType = Item_Ammo_GunBullet; Is there anything the...
26
by: Neville Lang | last post by:
Hi all, I am having a memory blank at the moment. I have been writing in C# for a number of years and now need to do something in VB.NET, so forgive me such a primitive question. In C#, I...
6
by: aznimah | last post by:
hi, i'm work on image comparison. i'm using the similarity measurement which i need to: 1) convert the image into the binary form since the algorithm that i've use works with binary data for the...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.