Just discovered this C# tidbit called the out method parameter. Let’s say you have a method:
public String ReplaceAll(String toReplace, String replaceWith)
and you want to know how many replacements were actually made. With a regular method you can only return the modified string. The out method parameter gives you the ability to return another variable. The modified method would look like this:
public String ReplaceAll(String toReplace, String replaceWith, out int numReplaced)
and then concretely:
String myString = “aaron”;
int replaced;
myString.ReplaceAll(“a”, “k”, out replaced);
Console.WriteLine(“The method ReplaceAll() replaced ” + replaced + ” characters.”);
Similar idea in the ref method parameter, but you have to initialize the variable before sending it to the method.
AJ, in your example, the method worked on an object. If I had done,
x = foo.someMethod(a, b, out z)
Would it still work? Ie, both x and z would have values?
yeah, I guess my concrete example was poorly written.. here’s a better example:
// method that uses “out”
public int Add(int a, int b, out String c) {
// this line modifies the String object ‘c’ in the calling code
c = “a + b = ” + (a + b);
// this line returns the result of adding a and b to the calling code
return (a + b);
}
// example of a use case
String c;
int result;
result = Add(3, 4, out c);
Console.WriteLine(“The method Add() performed the operation: ” + c + ” and the result was ” + result + “.”);
Make more sense that way?
AJ
Yes, out and ref modifiers are handy in some situtations. Here is another sample code by Jesse Liberty:
http://www.ondotnet.com/pub/a/dotnet/2002/02/11/csharp_traps.html?page=3
Trap # 10