Note that there are some explanatory texts on larger screens.

plurals
  1. POShould I Overload == Operator?
    text
    copied!<p>How does the <code>==</code> operator really function in C#? If it used to compare objects of class <em>A</em>, will it try to match all of <em>A</em>'s properties, or will it look for pointers to the same memory location (or maybe something else)?</p> <p>Let's create a hypothetical example. I'm writing an application that utilizes the Twitter API, and it has a <em>Tweet</em> class, which has all the properties of a single tweet: text, sender, date&amp;time, source, etc. If I want to compare objects of class <em>Tweet</em> for equivalence, can I just use:</p> <pre><code>Tweet a, b; if (a == b) { //do something... } </code></pre> <p>Will that <strong>check for equivalence of all the properties</strong> of the <em>Tweet</em> class between <em>a</em> and <em>b</em>?</p> <p>If not, <strong>would the correct approach be to overload the <code>==</code> operator</strong> to explicitly check for equivalence of all the fields?</p> <p><strong>UPDATE:</strong> From the first two answers, am I right in assuming:</p> <ul> <li>If the <code>==</code> operator or <em>Equals</em> method is not overloaded for a class, the <code>==</code> operator for the <em>object</em> class is used.</li> <li>The <code>==</code> operator for the <em>object</em> class checks for equality in memory location.</li> <li>I have to overload the <code>==</code> operator or the <em>Equals</em> method to accomplish this task.</li> <li>In the overload, I have to check for equivalence in properties manually, so <strong>there is no way to do it semi-automatically, say, in a loop</strong>, right?</li> </ul> <p><strong>UPDATE #2:</strong> Yuriy made a comment that it is possible to do check for equivalence in properties in the <code>==</code> operator with <strong>reflection</strong>. How can this be done? Could you give me some sample code? Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload