Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 629
5YrsLaterDBA Avatar asked Mar 01 '10 21:03

5YrsLaterDBA


1 Answers

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.

like image 172
Jon Skeet Avatar answered Sep 30 '22 00:09

Jon Skeet