Default Equals behavior.
suggest changeEquals
is declared in the Object
class itself.
public virtual bool Equals(Object obj);
By default, Equals
has the following behavior:
- If the instance is a reference type, then
Equals
will return true only if the references are the same. - If the instance is a value type, then
Equals
will return true only if the type and value are the same. string
is a special case. It behaves like a value type.
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
//areFooClassEqual: False
Foo fooClass1 = new Foo("42");
Foo fooClass2 = new Foo("42");
bool areFooClassEqual = fooClass1.Equals(fooClass2);
Console.WriteLine("fooClass1 and fooClass2 are equal: {0}", areFooClassEqual);
//False
//areFooIntEqual: True
int fooInt1 = 42;
int fooInt2 = 42;
bool areFooIntEqual = fooInt1.Equals(fooInt2);
Console.WriteLine("fooInt1 and fooInt2 are equal: {0}", areFooIntEqual);
//areFooStringEqual: True
string fooString1 = "42";
string fooString2 = "42";
bool areFooStringEqual = fooString1.Equals(fooString2);
Console.WriteLine("fooString1 and fooString2 are equal: {0}", areFooStringEqual);
}
}
public class Foo
{
public string Bar { get; }
public Foo(string bar)
{
Bar = bar;
}
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents
2 Literals
18 Regex
19 DateTime
20 Arrays
22 Enum
23 Tuples
25 GUID
26 BigInteger
28 Looping
29 Iterators
30 IEnumerable
35 Dynamic type
37 Casting
41 Interfaces
47 Methods
52 Keywords
53 Recursion
57 Inheritance
58 Generics
62 Reflection
65 LINQ Queries
66 LINQ to XML
68 XmlDocument
69 XDocument
79 Diagnostics
80 Overflow
86 Properties
89 Events
93 Structs
94 Attributes
95 Delegates
97 Networking
102 Action Filters
103 Polymorphism
104 Immutability
105 Indexer
107 Stream
108 Timers
109 Stopwatches
110 Threading
112 Async Await
114 BackgroundWorker
117 Lock Statement
118 Yield Keyword
121 Func delegates
124 ICloneable
125 IComparable
127 Using SQLite
128 Caching
129 Code Contracts
136 Pointers
144 Hash Functions
146 Cryptography
148 C# Script
149 Runtime Compile
150 Interoperability
156 Contributors