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 u/inconspicuous 06 Jul 2015 12:40
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:
A good resource is https://msdn.microsoft.com/en-us/library/ms229017
0 u/ArgumentException [OP] 06 Jul 2015 16:29
Thanks for clearing this up! I appreciate it
0 u/14d2025 06 Jul 2015 16:35
When do you use structs vs classes I recommend entire course in this series. Very informative for beginners.
0 u/Hjorthenify 07 Jul 2015 19:04
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