paul
paul

Reputation: 567

checkeditems possible unintended reference comparison

I got this code although it works fine but its giving me a warning(possible unintended reference comparison) on the code (st.staff_name == chk). I puzzled why this is. Help would be appreciated. Thank you.

    private void buttonCreateSubmit_Click(object sender, EventArgs e)
    {
        Body body = new Body
        {
            body_content = richTextBoxBody.Text
        };

        tnDBase.AddToBodies(body);
        tnDBase.SaveChanges();

        var genid = tnDBase.Genres.Single(g => g.genre_name == comboBoxGenre.Text);

        Article article = new Article()
        {
            article_name = textBoxTitle.Text,
            genre_id = genid.genre_id,
            status_id = 3,
            body_id = body.body_id
        };

        tnDBase.AddToArticles(article);
        tnDBase.SaveChanges();

        if (checkedListBoxWriter.CheckedItems.Count != 0)
        {
            for (int x = 0; x <= checkedListBoxWriter.CheckedItems.Count - 1; x++)
            {
                var chk = checkedListBoxWriter.CheckedItems[x];
                var staf = tnDBase.Staffs.SingleOrDefault(st => st.staff_name == chk);
                WriterLog writerlog = new WriterLog()
                {
                    article_id = article.article_id,
                    staff_id = staf.staff_id
                };
                tnDBase.AddToWriterLogs(writerlog);
                tnDBase.SaveChanges();
            }
        }
    }

Upvotes: 0

Views: 1690

Answers (2)

benjamin
benjamin

Reputation: 1087

I am guessing that it is giving you the warning because you are taking the default value of var chk = checkedListBoxWriter.CheckedItems[x]; and comparing it to a database item. Try and ask for a specific value var chk = checkedListBoxWriter.CheckedItems[x].Value; or force chk to be a string.

Upvotes: 0

Adam Robinson
Adam Robinson

Reputation: 185663

You're getting this warning because you're comparing a string to an object. Like all custom operators, the custom == operator for the string type (which compares the value of the string rather than whether or not the two strings have reference equality, which they might not) can only work when both operands are string references.

If you know that the items in CheckedItems will be strings, then just cast it to a string:

SingleOrDefault(st => st.staff_name == (string)chk);

Upvotes: 2

Related Questions