![]() |
|
Methods in C#, Free online C# Programming Tutorial... |
| Lessons | C# Methods |
|
ref Keyword In C#, as in C++, a method can only have one return value. You overcome this in C++ by passing pointers or references as parameters. In C#, with value types, however, this does not work. If you want to pass the value type by reference, you mark the value type parameter with the ref keyword as shown below. public void foo(int x, ref int y) Note that you need to use the ref keyword in both the method declaration and the actual call to the method. someObject.foo(a, ref b); out Parameters C# requires definite assignment, which means that the local variables, a, and b must be initialized before foo is called. int a, b; b = 0; someObject.foo(ref a, b); // not allowed a has not been initialized a = 0; b =0; someObject.foo(ref a, b); // now it is OK This is unnecessarily cumbersome. To address this problem, C# also provides the out keyword, which indicates that you may pass in un-initialized variables and they will be automatically initialized by the compiler. public void foo(int x, ref int y, out int z) a = 0; b = 0; someObject.foo(ref a, b, out c); // no need to initialize c params Keyword One can pass an arbitrary number of types to a method by declaring a parameter array with the 'params' modifier. Types passed as 'params' are all passed by value. This is elaborated with the help of the following example: public static void Main(){ double a = 1; int b = 2; int c = 3; int d = totalIgnoreFirst(a, b, c); } public static int totalIgnoreFirst(double a, params int[] intArr){ int sum = 0; for (int i=0; i < intArr.Length; i++) sum += intArr[i]; return sum; }
Next >>> Lesson No. 17: C# Method Hiding and Overriding
|