Learner
Learner

Reputation: 1634

Please tell why two references are same for string object in case of string( Code written below)

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class ddLlSTeXPT : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Page_Load(object sender, EventArgs e)
    {
          string pass="infoways";

          if(txtbx.Text==pass)
          Response.Write("hello U Logged In");
          else
          Response.Write("hello U cant log In");
    }
}

But it print correctly if the text in textbox is "infoways". How thesepoint to same refrence as the two objects are assigned different memory?

Upvotes: 0

Views: 113

Answers (1)

Cody Gray
Cody Gray

Reputation: 244752

I'm not entirely sure what you're asking here. The code that you've posted tests to see if the text in the TextBox control is equivalent to the string "infoways". If so, it displays the message "hello U Logged In"; if not, it displays the message "hello U can't log In". Your code appears to be working as expected.

The == operator is overloaded for the String class, so when you write string1 == string2, that is essentially equivalent to String.Equals(string1, string2). Unlike other objects, the == operator does not compare reference equality for String types. As explained by the documentation:

Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive.

Upvotes: 5

Related Questions