Value types are normally primitives and are stored directly in memory - on the stack, nice and fast. (Except string)
Reference types are normally larger objects and are accessed through a reference - like a pointer.
Form f1; // Allocate the reference
f1 = new Form(); // Allocate the object
In C#, parameters are (by default) passed by value, meaning that they are implicitly copied when passed to the method. For value-type parameters, this means physically copying the instance, while for reference-types it means copying a reference.
Point myPoint = new Point (0, 0); // a new value-type variable
Form myForm = new Form(); // a new reference-type variable
Test (myPoint, myForm); // Test is a method defined below
void Test (Point p, Form f)
{
p.X = 100; // No effect on MyPoint since p is a copy
f.Text = "Hello, World!"; // This will change myForm's caption since
// myForm and f point to the same object
f = null; // No effect on myForm
}
We can change the way parameters are marshalled with the ref modifier. When passing by "reference", the method interacts directly with the caller's arguments. In the example below, you can think of the parameters p and f being replaced by myPoint and myForm:
Point myPoint = new Point (0, 0); // a new value-type variable
Form myForm = new Form(); // a new reference-type variable
Test (ref myPoint, ref myForm); // pass myPoint and myForm by reference
void Test (ref Point p, ref Form f)
{
p.X = 100; // This will change myPoint's position
f.Text = "Hello, World!"; // This will change MyForm's caption
f = null; // This will nuke the myForm variable!
}
Enums and Structs are the only object types that are created on the stack and are beneficial you need to store data and the cost of managing the heap by way of a reference type outways the benefit as the amount of data to be stored is relatively small.
Why is there string and String, int and Int????
In .Net for every Value type there is an Equivalent Class that is a reference class.
e.g.
int (value type) and System.Int (reference type)
bool (value type) System.Bool (reference type)
These are just shorthand and the onjects themselves have exactly the same functionality.
Question marks after param mean the param can be null - this only applies to value types - not reference, so no strings.
void myMethod(Datetime? nullabledatetime)