C # identify traps with equal objects

Source: Internet
Author: User

 

See the following test code:

 

Object a = 11;

Object B = 11;

 

Console. WriteLine (a = B); // output false

In actual development, it may not be so intuitive. For example, in the following scenario, we need to check whether the fields in Datarow are equal. You may write as follows:

 

DataRow hbrow = needAddRows. Where (p => p ["dh"] = dr ["dh"]). FirstOrDefault (); // dr is a datarow. Congratulations! You won the prize! :) Hbrow is always null. Because p ["dh"] and dr ["dh"] are of the object type. However, if you output:

 

? P ["dh"]. GetType (). Name // output Int32. This is caused by the binning and unboxing of the Value Type ValueType of the Object.

 

Let's take a look at the following test code:

 

Object a = 11; object B = 11; Console. WriteLine (a = B); // equivalent to ReferenceEquals. Of course, the comparison references are not equal! Console. writeLine (object. referenceEquals (a, B); // falseConsole. writeLine (object. equals (a, B); // trueConsole. writeLine (. equals (B); // true

Equals is recommended for comparing Datarow!

 

From: slmk

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.