In Java there are "==" and "equals" operator for reference types and "==" for value types. for reference type, "==" means both objects point to the same location and "equals" means their values are the same. does C# has similar operators for value type and reference types?
Well, == can be overloaded for reference types. For example:
string a = new string('x', 10);
string b = new string('x', 10);
Console.WriteLine(a == b); // True
Console.WriteLine(Object.ReferenceEquals(a, b)); // False
Unless it's overloaded, == means "reference equality" aka "object identity" for reference types. (As Marc says, you may override Equals
without overloading ==.)
For value types, you have to overload == otherwise the C# compiler won't let you use it for comparisons. .NET itself will provide an implementation of Equals
which usually does the right thing, but sometimes slowly - in most cases, if you write your own custom value type you'll want to implement IEquatable<T>
and override Equals
as well - and quite possibly overload various operators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With