Class vs Struct — C#

The C# language is an extensive thing to learn and any dedicated developer may spend several years studying and learning the language and it would not be enough to know absolutely everything in C#. There are some basic concepts that could be missed even by senior developers, which is normal considering many concepts and features are being daily used but without notice that they are there.

The use of structs is one of those examples, there are tons of implementations and sample among native .NET libraries, but it is not common to see they being created by developers. I judge that there are two main reasons for that:

  1. There is a consense in a project that structs are suitable for the specific scenario.

  2. Missing knowledge on how structs work and when they should be accordingly used.

Before we start walking through the theory behind the difference between classes and structs, it is important to take a look at the syntax of each of them.

The following examples represent a class and a struct for handling Passport information, including store and validate the underlying data.

Passport class

Passport class

The passport class contains three fields: number, expiration, and country. It was kept simple for demonstration purposes. In a real scenario, the structure would be different. The implementation of the validation method is missing as well as it is not relevant for this article.

Passport struct

On the other hand, a struct version of the Passport class would be like the image below:

At the first moment, the only difference between the class and struct was the related keywords “class” and “struct” in terms of syntax. However, what occurs behind the scenes in runtime is completely different and might affect the behaviour of the system significantly.

To start with the characteristics of each one, I’d like to emphasize what happens when we copy a struct and when we copy an instance of any class.

In lines 9 and 10, an object of the Passport class is created with the number “123” and just after that a second Passport is created, receiving the first passport as an assignment. And finally, in line 14, the number of the second passport is changed to “456”. If we print in console the values for both of the passports, we get the following result: