Valuetypes in C#

After some confusion on IRC on the differences between classes and valuetypes (D8: records)
a valuetype in C# is a lot like a class, except that it a few differences:

  • It always descends from System.ValueType directly
  • It’s always sealed (no other structure can descend from it)
  • Constructors, though possible are not called when you use them (speed reasons) unless explicitly called

The other difference, and also the most important one is the way it’s stored. Structures are stored where you define them, which is different from classes because they are stored as a pointer and have to be created on the heap with the new operator. A reason to use structures instead of classes is usually speed, creating an array of structures is a single allocation for all items at once, when using classes, it’s an allocation for the pointers, and for each item a seperate allocation for the class itself. One downside to valuetypes is that you can ‘t create subclasses and overriding methods is limited to the ones defined in System.ValueType and System.Object.

Carlo Kok

Read more posts by this author.