C#: 12-out & ref Keywords

out : Updating a Value type from called function

public static void ValueTypes()
{
    var x = 2;
    Console.WriteLine("ValueTypes: var x=2");
    Console.WriteLine("ValueTypes: Five(x): Before: {0}", x);
    // passes the VALUE to func so WILL NOT CHANGE ITS VALUE
    Console.WriteLine("ValueTypes: Five(x):calling..");
    Five(x);
    Console.WriteLine("ValueTypes: Five(x): AFTER: {0}", x);
}


 

static void Five(int a)
{
    a = 5;
    Console.WriteLine("ValueTypes: IN..Fix(int a): assigning a=5");
}


 


 

public static void ReferenceTypes()
{
    var x = 2;
    Console.WriteLine("ReferenceTypes: var x=2");
    Console.WriteLine("ReferenceTypes: Six(out int a): Before: {0}", x);
    // passes the VALUE to func 
    //  BUT... 'out' keyword allows that value to be output back to the value in memory
    // so WILL CHANGE ITS VALUE
    Console.WriteLine("ReferenceTypes: Six(out x):calling..");
    Six(out x);
    Console.WriteLine("ReferenceTypes: Six(out int a): AFTER: {0}", x);
}


 


 

static void Six(out int a)
{
    a = 6;
    Console.WriteLine("ReferenceTypes: IN..Six(out int a): assigning a=6");
}


 

Output

ValueTypes: var x=2
ValueTypes: Five(x): Before: 2
ValueTypes: Five(x):calling..
ValueTypes: IN..Fix(int a): assigning a=5
ValueTypes: Five(x): AFTER: 2
ReferenceTypes: var x=2
ReferenceTypes: Six(out int a): Before: 2
ReferenceTypes: Six(out x):calling..
ReferenceTypes: IN..Six(out int a): assigning a=6
ReferenceTypes: Six(out int a): AFTER: 6


 

ref : updating passed variable AND using self-referencing calculations

public static void ValueTypesWithRef()
{
    var x = 2;
    Console.WriteLine("ValueTypesWithRef: var x=2");
    Console.WriteLine("ValueTypesWithRef: Doubled(ref int a): Before: {0}", x);
    // passes the VALUE to func 
    //  BUT... 'out' keyword allows that value to be output back to the value in memory
    // so WILL CHANGE ITS VALUE
    Console.WriteLine("ValueTypesWithRef: Doubled(ref x):calling..");
    Doubled(ref x);
    Console.WriteLine("ValueTypesWithRef: Doubled(ref int a): AFTER: {0}", x);
}


 

static void Doubled(ref int a)
{
    //ref keyword allows self-referencing calculations
    // AND updating the passed variable
    a = a * 2;
    Console.WriteLine("ValueTypesWithRef: IN..Doubled(ref int a): assigning a=a*2");
}

Output

ValueTypesWithRef: var x=2
ValueTypesWithRef: Doubled(ref int a): Before: 2
ValueTypesWithRef: Doubled(ref x):calling..
ValueTypesWithRef: IN..Doubled(ref int a): assigning a=a*2
ValueTypesWithRef: Doubled(ref int a): AFTER: 4
Tags