When you define your own type, that type inherits the functionality defined by the Equals method of its base type. The following table lists the default implementation of the Equals method for the major categories of types in the .NET Framework. (MSDN)
When we’re comparing two structs using the Equals method, if we don’t override the Equals method, it uses the underlying value type “Equals” method. When this underlying Equals method is called, if our struct contains only value members then Equals method just compares the individual bytes in memory of the two instances we’re comparing. If, however, any of the members in our struct are not value types the underlying Equals method actually uses reflection to compare the members in each instance. When reflection is used, it’s usually quite expensive, and that’s why with reference type Equality takes so much longer as reflection was being used to determine the equality.
1
2
3
4
5
6
| internal struct OnlyValueType { public int A { get ; set ; } public int B { get ; set ; } public string Name { get ; set ; } } |
Now override Equal method in struct,
1
2
3
4
5
6
7
8
9
10
11
12
13
| internal struct OnlyValueType { public int A { get ; set ; } public int B { get ; set ; } public string Name { get ; set ; } public override bool Equals( object obj) { var objAfterCast = (OnlyValueType)obj; return A == objAfterCast.A && B == objAfterCast.B && Name == objAfterCast.Name; } } |
See the performance now