The type values in c# is catogoried into reference type and value type. Value type is straight forward, it is just like normal variable value that we stored in the stack memory. However, compiler store reference type in the heap memory. When we create an instance of class, we have the following code:
Form f1; // Allocate the reference
f1 = new Form(); // Allocate the object
f2 = f1;
f1 and f2 are pointing to the same object which is Form. In this case, if we pass f1 into a method, a local of copy of f1 is created. The changes made on the local copy will affect f1, but it is not true for null case. It is because if we set null to the local copy, only the local copy is destroyed but not f1.
As mentioned, value type is stored in stack, the stack is popped when the variable is not in use anymore. Reference type is like a room that filled with objects, which reference to an object is provided. This reference can be located in stack or it could be another heap-object. In the above example, f1 is stored in stack while Form object is stored in heap. For the below case, the reference is another heap-object.
Font f = new Font("Arial",10);
f1.font = f;
f is another reference in heap,which is pointing to Font class object.
For value type variable, it is not possible to modify them in the method. Let’s consider the following code:
public void test(int x)
{
x = 5 ;
return;
}
It is not possible for us to modify variable x in the method. However, with keyword ref, we are able to make the changes on variable x. It is because we pass the variable by reference.
public void test(ref int x)
{
x = 5 ;
return;
}
It is possible to use keyword out instead of ref. The main difference between them is that ref must be initialized before it is passed into the method.