Thursday, May 15, 2008

[C#] Parameter Passing - "ref" and "out"

Before I get into parameter passing...

There are two different types in C#
1) Value-Types [http://msdn2.microsoft.com/en-us/library/s1ax56ch(VS.71).aspx]
- Structs
* Built in --> Numeric Types [int, double etc...], Bool.
* User defined
- Enums
- Unlike reference types, it is not possible for a value type to contain the null value.
2) Reference-Types [http://msdn2.microsoft.com/en-us/library/490f96s2(VS.71).aspx <-- seems to be broken]
- class, delegate, interface, object, string.
Parameter Passing
All value-type parameters are what we call "pass by value" and all changes made to that value in the function will have no affect on the original data.
All reference-type parameters are "pass by reference" and all changes made to it will be reflected in the original.
If you want to force a parameter to be pass by reference then we use the "ref" or "out" keyword.
Differences Between "ref" and "out"
"out": an out parameter of an array type must be assigned before it is used; that is, it must be assigned by the callee.
For example:
public static void MyMethod(out int[] arr)
{
arr = new int[10]; // definite assignment of arr
}
C#
"ref": a ref parameter of an array type must be definitely assigned by the caller. Therefore, there is no need to be definitely assigned by the callee. A ref parameter of an array type may be altered as a result of the call. For example, the array can be assigned the null value or can be initialized to a different array.
For example:
public static void MyMethod(ref int[] arr)
{
arr = new int[10]; // arr initialized to a different array
}

No comments: