Structs vs Classes in C#

9    06 Jul 2015 12:30 by u/ArgumentException

Is there anyone here that could clarify whether there's a benefit of using structs as opposed to using container-classes? Are structs better for that kind of thing (faster? less memory usage?).

Thanks

5 comments

9

An important thing to note is that a class is a reference type (allocated on the heap) while a struct is a value type (allocated on the stack). Since structs are on the stack, allocation and deallocation are generally faster. There are other differences between value and reference types that you can research further.

Consider defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

Avoid defining a struct unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (int, double, etc.).
  • It has an instance size under 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.

A good resource is https://msdn.microsoft.com/en-us/library/ms229017

0

Thanks for clearing this up! I appreciate it

0

When do you use structs vs classes I recommend entire course in this series. Very informative for beginners.

0

I'd like to add that when copying a struct its done by value(resulting in the two structs being independent) as opposed to copying a class then only the reference is copied which essentially means that they both point to the same place in memory. http://www.albahari.com/valuevsreftypes.aspx