Comparing two strings for equality

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • zacksoniar
    New Member
    • Sep 2007
    • 45

    Comparing two strings for equality

    Generally i write this kind of code in my programs to compare two strings & it works fine.
    Code:
    string s="Hello";
    
    if(s=="Hello")
    {
       code to execute.
    }
    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
  • ThatThatGuy
    Recognized Expert Contributor
    • Jul 2009
    • 453

    #2
    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 equalsIgnoreCas e() which checks the object or string irrespective of its case

    Comment

    • zacksoniar
      New Member
      • Sep 2007
      • 45

      #3
      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??

      Comment

      • jkmyoung
        Recognized Expert Top Contributor
        • Mar 2006
        • 2057

        #4
        When you say 'right' results, are you saying it returns false, or it returns true?
        Could be some sort of compiler optimization.

        Comment

        • Christian Binder
          Recognized Expert New Member
          • Jan 2008
          • 218

          #5
          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.

          Comment

          • zacksoniar
            New Member
            • Sep 2007
            • 45

            #6
            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....rig ht results means true....when i say if(s=="Hello"), it returns true & executes the code inside of if block..

            Thanks all for ur replies...

            Comment

            Working...