By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,238 Members | 1,804 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,238 IT Pros & Developers. It's quick & easy.

Comparing two strings for equality

P: 45
Generally i write this kind of code in my programs to compare two strings & it works fine.
Expand|Select|Wrap|Line Numbers
  1. string s="Hello";
  2.  
  3. if(s=="Hello")
  4. {
  5.    code to execute.
  6. }
  7.  
but i want to know whether in C#, it actually compares two string values or is it comparing the addresses of two strings. How am i getting correct results?


Also,it will be very nice if you guys can tell me how above code behaves in Java
Mar 23 '10 #1

✓ answered by Christian Binder

Have a look at http://msdn.microsoft.com/en-us/libr...=VS.90%29.aspx

The ==-Operator calls the Equals()-method as far as I've understood it.

Share this Question
Share on Google+
5 Replies


ThatThatGuy
Expert 100+
P: 449
The code you'd written above doesn't check for equality... it just checks if the two strings refer to the same address...

you should use equals() method which checks for real equality...
this things works for all languages specially Object Oriented languages

In java you have an additional method equalsIgnoreCase() which checks the object or string irrespective of its case
Mar 23 '10 #2

P: 45
Thanks ThatThatGuy for ur instant reply..

but then how s=="Hello" gave me right results so far..see "Hello" is just a literal created at that moment.It will be at different address.

I have deployed a project using that kind of technique & it is working fine.why is it so??
Mar 23 '10 #3

jkmyoung
Expert 100+
P: 2,057
When you say 'right' results, are you saying it returns false, or it returns true?
Could be some sort of compiler optimization.
Mar 23 '10 #4

Expert 100+
P: 218
Have a look at http://msdn.microsoft.com/en-us/libr...=VS.90%29.aspx

The ==-Operator calls the Equals()-method as far as I've understood it.
Mar 23 '10 #5

P: 45
Thanks for ur reply ChBinder ...it helped alot.

I asked my friend about how it works in JAVA.he said == only checks for addresses in JAVA.....so,C# is one step ahead... :D :D

& yes jkmyoung....right results means true....when i say if(s=="Hello"),it returns true & executes the code inside of if block..

Thanks all for ur replies...
Mar 24 '10 #6

Post your reply

Sign in to post your reply or Sign up for a free account.