Understanding values and references

Quick reference

To

Do this

Copy a value type variable

Simply make the copy. Because the variable is a value type, you will have two copies of the same value. For example:

int i = 42; 
int copyi = i;

Copy a reference type variable

Simply make the copy. Because the variable is a reference type, you will have two references to the same object. For example:

Circle c = new Circle(42); 
Circle refc = c;

Declare a variable that can hold a value type or the null value

Declare the variable by using the ? modifier with the type. For example:

int? i = null;

Pass an argument to a ref parameter

Prefix the argument with the ref keyword. This makes the parameter an alias for the actual argument rather than a copy of the argument. The method may change the value of the parameter, and this change is made to the actual argument rather than to a local copy. For example:

static void Main() 
{ 
    int arg = 42; 
    doWork(ref arg); 
    Console.WriteLine(arg); 
}

Pass an argument to an out parameter

Prefix the argument with the out keyword. This makes the parameter an alias for the actual argument rather than a copy of the argument. The method must assign a value to the parameter, and this value is made to the actual argument. For example:

static void Main() 
{ 
    int arg; 
    doWork(out arg); 
    Console.WriteLine(arg); 
}

Box a value

Initialize or assign a variable of type object with the value. For example:

object o = 42;

Unbox a value

Cast the object reference that refers to the boxed value to the type of the value variable. For example:

int i = (int)o;

Cast an object safely

Use the is operator to test whether the cast is valid. For example:

WrappedInt wi = new WrappedInt(); 
... 
object o = wi; 
if (o is WrappedInt temp) 
{ 
    ... 
}

Alternatively, use the as operator to perform the cast, and test whether the result is null. For example:

WrappedInt wi = new WrappedInt(); 
... 
object o = wi; 
WrappedInt temp = o as WrappedInt; 
if (temp != null) 
  ...