Value parameter ,reference parameter and output parameter differences

Reference parameters must be assigned required the outside method !

Output parameters non required assign but the method inside must be assign !

Here this ->


class Program
{
static void Main(string[] args)
{
MyClass param1;
int param2 = 50;

//Write1(param1, param2);
//Write2(ref param1, ref param2);
//Write3(out param1, out param2);

Console.WriteLine("(default) param 1 : {0} - param 2 : {1}", param1.Val, param2);

Console.ReadLine();
}

public static void Write1(MyClass param1, int param2)
{
param1.Val += 10;
param2 += 10;
Console.WriteLine("(value) param 1 : {0} - param 2 : {1}", param1.Val, param2);
}

// ref parameters must be assigned required
public static void Write2(ref MyClass param1, ref int param2)
{
param1.Val += 10;
param2 += 10;
Console.WriteLine("(reference) param 1 : {0} - param 2 : {1}", param1.Val, param2);
}

// out parameter must be assigned in method parateter
public static void Write3(out MyClass param1, out int param2)
{
param1 = new MyClass();
param2 = 50;

param1.Val += 10;
param2 += 10;
Console.WriteLine("(reference) param 1 : {0} - param 2 : {1}", param1.Val, param2);
}
}

public class MyClass
{
public int Val { get; set; }

public MyClass()
{
this.Val = 50;
}
}

Advertisements

#csharp, #output-parameter, #reference-parameter, #value-parameter