out method parameter in C#

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.

3 thoughts on “out method parameter in C#”

  1. 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

Leave a Reply

Your email address will not be published. Required fields are marked *