Distinction between output and reference parameter

>>output parameter do not need to initialize before the passed to the method.it must assign when before  exiting the method calling.

>>reference parameter must assign the before passed to the method. The reason is that passing the reference to an existing variable. If not assign works as unassigned variable.

// Returning multiple output parameters.

static void FillTheseValues(out int a, out string b, out bool c)

{

a = 9;

b = “Enjoy your string.”;

c = true;

}

static void Main(string[] args)

{

Console.WriteLine(“***** Fun with Methods *****”);

int i; string str; bool b;

FillTheseValues(out i, out str, out b);

Console.WriteLine(“Int is: {0}”, i);

Console.WriteLine(“String is: {0}”, str);

Console.WriteLine(“Boolean is: {0}”, b);

Console.ReadLine();

}

// Reference parameters.

public static void SwapStrings(ref string s1, ref string s2)

{

string tempStr = s1;

s1 = s2;

s2 = tempStr;

}

This method can be called as follows:

static void Main(string[] args)

{

Console.WriteLine(“***** Fun with Methods *****”);

string str1 = “Flip”;

string str2 = “Flop”;

Console.WriteLine(“Before: {0}, {1} “, str1, str2);

SwapStrings(ref str1, ref str2);

Console.WriteLine(“After: {0}, {1} “, str1, str2);

Console.ReadLine();

}

Leave a Reply