Help with "ref" and "out" in C# .NET 3.5 2008
- "ref" is by reference
- It does not give a compiler error if it was not passed in the argument list for the function
- It gives you the ability to modify the pointer of the original object
- It is a great way to pass structures around in code because it does not make a "by value" copy of them
- Parameter must be initialized before calling the function
- "ref" prefix exists when defining the function and when calling it (making it obvious that this is a by reference call)
public void SimpleSwap(ref String string1, ref String string2)
{// store the pointer of string1
String temp = string1;// set string1's pointer to point to string2
string1 = string2;// set string2's pointer to point to string1 (HINT: this is not pointing to string2)
string2 = temp;
}
// ... code using this ...
String string1 = "ABC";
String string2 = "DEF";
SimpleSwap(ref string1, ref string2);// string1 now points to "DEF"// string2 now points to "ABC"
- "out" is by reference
- The parameter must be assigned or you get a compile error
- A new object is created and returned (the variable you passed in points to the one created inside of the function)
- "out" parameters do not need to be initialized
- This is a great way to fill structures
- It allows the language to safely handle multiple return values without the need for new objects/structs
- "out" prefix exists when defining the function and when calling it (making it obvious that this variable will be initialized by the function call)
Example of a Function Returning Multiple Values in C#
public void GetCoordinates(out int x, out int y)
{x = 5;y = 9;}// ... code using this ...
int x;int y;
GetCoordinates(x,y);
// x is now 5// y is now 9

