Free mag vol1 | Page 189

CHAPTER 4  CORE C# PROGRAMMING CONSTRUCTS, PART II static void Main(string[] args) { Console.WriteLine("***** Fun with Methods *****"); ... // No need to assign initial value to local variables // used as output parameters, provided the first time // you use them is as output arguments. int ans; Add(90, 90, out ans); Console.WriteLine("90 + 90 = {0}", ans); Console.ReadLine(); } The previous example is intended to be illustrative in nature; you really have no reason to return the value of your summation using an output parameter. However, the C# out modifier does serve a very useful purpose: it allows the caller to obtain multiple outputs from a single method invocation. // Returning multiple output parameters. static void FillTheseValues(out int a, out string b, out bool c) { a = 9; b = "Enjoy your string."; c = true; } The caller would be able to invoke the FillTheseValues() method. Remember that you must use the out modifier when you invoke the method, as well as when you implement the method: 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(); Finally, always remember that a method that defines output parameters must assign the parameter to a valid value before exiting the method scope. Therefore, the following code will result in a compiler error, as the output parameter has not been assigned within the method scope: static void ThisWontCompile(out int a) { Console.WriteLine("Error! Forgot to assign output arg!"); } 124