Value Type vs Reference Type

The Types in .NET Framework are either treated by Value Type or by Reference 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.

Example: Struct & all the built-in numeric 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.

Example: Class

By default an 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

var myObj = new SomeClass();
SomeMethodThatChangesTheObjectValues(ref myObj)
//do something, perhaps pass back to the view?

References

Leave a Reply