Free mag vol1 | Page 190

CHAPTER 4  CORE C# PROGRAMMING CONSTRUCTS, PART II The ref Modifier Now consider the use of the C# ref parameter modifier. Reference parameters are necessary when you wish to allow a method to operate on (and usually change the values of) various data points declared in the caller’s scope (such as a sorting or swapping routine). Note the distinction between output and reference parameters: • Output parameters do not need to be initialized before they passed to the method. The reason for this is that the method must assign output parameters before exiting. • Reference parameters must be initialized before they are passed to the method. The reason for this is that you are passing a reference to an existing variable. If you don’t assign it to an initial value, that would be the equivalent of operating on an unassigned local variable. Let’s check out the use of the ref keyword by way of a method that swaps two string variables (of course, any two data types could be used here, including int, bool, float, and so on): // 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(); } Here, the caller has assigned an initial value to l ocal string data (str1 and str2). After the call to SwapStrings() returns, str1 now contains the value "Flop", while str2 reports the value "Flip": Before: Flip, Flop After: Flop, Flip 125