The C# Type System by Steve Love

The C# Type System by Steve Love

Author:Steve Love
Language: eng
Format: epub, mobi
Publisher: No Starch Press


Structs and Equality

Since value type instances are copied by value, every value type variable is a distinct instance of the type, so two instances can never compare equal according to their identity. We need to compare their values, meaning that we compare their state instead. This usually involves comparing each field of one instance with the corresponding field of another.

Structs implicitly inherit from the System.ValueType class, which provides the value-based equality required for value types. By default, calling Equals on a struct will use the ValueType implementation, because Equals is a virtual method. As Chapter 2 explained, for its implementation, the ValueType.Equals method relies on reflection, which provides the correct behavior for any possible struct type at the expense of performance. While it might not be the most efficient comparison, the ValueType.Equals method uses each field’s Equals method to compare the field with its companion, so it has the behavior we require. Similarly, ValueType also overrides GetHashCode to create hash codes based on a struct’s fields, ensuring that any two struct instances that are equal according to Equals also generate identical hash codes.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.