Tech Blog

Classes Versus Struct

Earlier in my programming career I was more fond of structs over classes. However I quickly came to realize the limitations of a struct and how to, in most cases, forgo them for a very well designed class. One of the main issues I was having was declaring every variable in creating the struct which I found to be a limitation so in this post I will go over some of the research I did and found to be useful in distinguishing the uses for a struct.

A class is a reference type while a struct is a value type. and a good understanding of the differences in the behavior of the two types is key for determining to wither create a value or a reference type object.

Class

Struct

  • Has to go through boxing and unboxing  in the memory, which for large scale applications can have an impact on the garbage collection
  • Reference assignments copy the reference to the class
  • Changes to an instance of a reference type affect all references pointing to the instance
  • Cheaper in memory, only gets unboxed when cast back to the value type.
  • Value type assignments copy the entire value, a struct cannot be declared without assigning all of its values
  • alue type instances are copied when they are passed by value

When to use structs:
Using a struct instead of a class is desirable if instances of the type are small short-lived or are embedded in other objects.

dan flan