In .NET, there are two categories of types known as the reference types and the value types. The Structs come under the category of value types and classes come under the reference types category. The known difference is that a reference type will live on the heap whereas a value type will live in line which means that wherever your variable is explained. A value type containing a variable includes the entire value type value which, in accordance to a struct, refers to a variable which contains the entire struct including all its fields. A reference type containing a variable includes a reference to another part in the storage where the actual value will exist. There is an advantage for this as the value types will always have a value included and a reference type will also have a null-reference included which means it does not refer to anything at the moment. Intrinsically, the reference types are implemented as pointers and knowing how variable assignment works, there are other behavioral patterns:
-
By copying the contents of a value type variable into another variable, it copies the entire content into a new variable which makes the two variables very distinct. In other words, after copying it, the changes to one will not affect the other one.
-
By copying the contents of a reference type variable into another variable, it will copy the reference, which states that you now have two references to the same somewhere else storage of the actual data. In other words, after copying it the changes in the data in one reference will appear to affect the other as well, but that is only because you are currently looking at the same data at both the places.
When you will declare your variables, the value type will live on the stack and the reference type will live on the stack as a pointer to somewhere in the heap storage where the actual memory lives