Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReferenceEquals returning false with strings

Tags:

c#

    private class global
    {
        public static int a = 0;
        public static int val = 0;
        public static int c = -1;
        public static string g = "";
    }
    private void button8_Click(object sender, EventArgs e)
    {
        global.a = global.a + 1;
        global.c = global.c + 1;
        string a = label2.Text;
        if (string.ReferenceEquals(a, global.g))
        {
            MessageBox.Show("a");
            //dataGridView1.Rows[global.c].Cells[1].Value = global.a;
            //dataGridView1.Rows[global.c].Cells[2].Value = global.val * global.a;
        }
        else
        {
            dataGridView1.Rows.Add(label2.Text, global.a, global.val);
        }
        global.g = label2.Text;
    }

If button8 is pressed again with label2.Text it should call MessageBox.Show() but somehow global.g = label2.text does not work. I tried with :

    string a = "";
    string b = "";
    if (string.ReferenceEquals(a, b))
    {
        MessageBox.Show("a");
    }

It works fine but then I change b to global.g it skips if...

like image 568
user3625236 Avatar asked Aug 23 '26 16:08

user3625236


1 Answers

As qqbenq states above... you should use String.Equals instead due to string interning.

You should NOT use reference equality to compare strings... as per Microsoft

you should not use ReferenceEquals to determine string equality.

And a bit more detail further down in the link...

Constant strings within the same assembly are always interned by the runtime. That is, only one instance of each unique literal string is maintained. However, the runtime does not guarantee that strings created at runtime are interned, nor does it guarantee that two equal constant strings in different assemblies are interned.

Specifically to answer your question... how should I change my code...

Edited as @Servy mentioned to use the static string.equals for the case where a is null.

    string a = "";
    string b = "";
    if (string.Equals(a, b))
    {
        MessageBox.Show("a");
    }

You should pretty much always use Equals for comparing reference types. Only use ReferenceEquals if you really want to check if they are not only equal but actually point to the same reference.

like image 120
Kevin Avatar answered Aug 25 '26 06:08

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!