开发者

C# == is different in value types and reference types?

In Java there are "==" and "equals" operator for reference types and "==" for value ty开发者_JAVA技巧pes. 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.


C# allows the == operator to be overloaded (and the Equals method to be overridden - although == and Equals don't have to mean the same thing).

If you want to mean "the same instance", then object.ReferenceEquals (for reference-types) is the best option. Value types default to internal equality.


Straight out of MSDN:

For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings.

Jon Skeet should be able to give you a perfect answer though :P


When should I use == and when should I use Equals?

http://blogs.msdn.com/csharpfaq/archive/2004/03/29/102224.aspx


This is precisely the way it works with .NET as well. The C# FAQ blog explains equals better:

The Equals method is just a virtual one defined in System.Object, and overridden by whichever classes choose to do so. The == operator is an operator which can be overloaded by classes, but which usually has identity behaviour.

For reference types where == has not been overloaded, it compares whether two references refer to the same object - which is exactly what the implementation of Equals does in System.Object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜