Search⌘ K
AI Features

How to Define Equality Amongst Objects

Explore the differences between value and reference types in C#, focusing on how equality is defined and tested in NUnit. Understand the concepts of value equality versus reference equality, learn when to override Equals and GetHashCode in reference types, and gain insights into struct equality implementation. This lesson equips you to write accurate and reliable equality assertions in your unit tests.

Introduction

C# provides for two main data types—value types and reference types. As per the Microsoft documentation1^{1}, a variable of a value type contains an instance of the type, whereas a variable of a reference type contains a reference to an instance of the type. By default, variable values are copied in three situations: on assignment, when passing an argument to a method, and when returning a method result. In the case of value type variables, the corresponding type instances are copied.

Equality comparisons are the fundamental operation that NUnit assertions use and therefore differentiating between the two types is important because it determines how equality comparisons are done.

Listing value and reference types

The list of value and reference types is shown below.

Value types

A data type is a value type if it holds a data value within its own memory space. It means the variables of these data types directly contain values.

  • Structure types
    • User-defined structs, e.g:
       public struct MyCustomStruct
       {
          public int X;
          public int
...