Data structures should expose data and have no methods

Structures differ from classes in that they use value equality in place of reference equality. Other than that, there is not much difference between a struct and a class.

There is a debate as to whether a data structure should make the variables public or hide them behind get and set properties. It is purely down to you which you choose, but personally I always think it best to hide data even in structs and only provide access via properties and methods. There is one caveat in terms of having clean data structures that are safe, and that is that once created, structs should not allow themselves to be mutated by methods and get properties. The reason for this is that changes to temporary data structures will be discarded.

Let's now look at a simple data structure example.

An example of data structure

The following code is a simple data structure:

namespace CH3.Encapsulation
{
public struct Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

public Person(int id, string firstName, string lastName)
{
Id = id;
FirstName = firstName;
LastName = lastName;
}
}
}

As you can see, the data structure is not that much different from a class in that it has a constructor and properties.

With this, we come to the end of the chapter and will now review what we've learned.