Comment on: Structs vs Classes in C#
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
Yeah, it can get really confusing. Technically a reference type has its reference passed by value into a function. It works like Java. I won't go into detail here because other people can explain it better than I can. Then you have strings, which are reference types that act like value types. Then there's the
refandoutmodifiers that you attached to method parameters.Hopefully I've given some areas that people can further look into. It's important to understand.
And just as a bonus note, turns out the CLR spec doesn't say you need to have value types on the stack; it's just commonly chosen for implementations. See http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx.