Reference and value Types

Reference and value types

A very important concept for understanding C# is the difference between reference and value types. The important difference is that reference types will be passed by reference, i.e., we will only pass a copy of the position of the object, and not a copy of the object itself. Any modification of the object will result in a modification of the original object.

The whole concept is quite similar to the concept of pointers in C. The only difference is that we do not actually have access to the address and we do not have to dereference the variable to get access to the values behind it. One could say that C# handles some of the things automatically that we would have to write by hand in C/C++

using System;
class Program
{
static void Main()
{
//A string is a class, which can be instantiated like this
string s = “Hi there”;
Console.WriteLine(s);//Hi there
ChangeString(s);
Console.WriteLine(s);//Hi there
ChangeString(ref s);
Console.WriteLine(s);//s is now a null reference
}
static void ChangeString(string str)
{
str = null;
}
static void ChangeString(ref string str)
{
str = null;
}
}

Please find below a very nice example for ref and out
using System;

class Program
{
static void Main()
{
int val = 0;
Example1(val);
Console.WriteLine(val); // Still 0.

Example2(ref val);
Console.WriteLine(val); // Now 2.

Example3(out val);
Console.WriteLine(val); // Now 3.
}
static void Example1(int value)
{
value = 1;
}

static void Example2(ref int value)
{
value = 2;
}

static void Example3(out int value)
{
value = 3;
}
}

The output will be:
0
2
3