The Types in .NET Framework are either treated by Value Type or by Reference Type.
Value Type
A Value Type stores its contents in memory allocated on the stack. When you created a Value Type, a single space in memory is allocated to store the value and that variable directly holds a value.
In C#, all the “things” declared with the following list of type declarations are Value types (because they are from System.ValueType):
1 | bool |
Reference Types
Reference Types are used by a reference which holds a reference (address) to the object but not the object itself. Because reference types represent the address of the variable rather than the data itself, assigning a reference variable to another doesn’t copy the data. Instead it creates a second copy of the reference, which refers to the same location of the heap as the original value.
All the “things” declared with the types in this list are Reference types (and inherit from System.Object… except, of course, for object which is the System.Object object):
1 | class |
By default a class instance as an object is passed to methods by value, to change this if you want the method to alter the object, pass it with the ref keyword.
1 | var myObj = new SomeClass(); |
References
- https://docs.microsoft.com/en-us/dotnet/csharp/basic-types
- http://net-informations.com/faq/general/valuetype-referencetype.htm
- https://stackoverflow.com/questions/5057267/what-is-the-difference-between-a-reference-type-and-value-type-in-c
- https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref
- https://www.c-sharpcorner.com/article/C-Sharp-heaping-vs-stacking-in-net-part-i