Thursday, January 05, 2006

Output Parameters from C# Method

I know that this is “old hat” to many but I am working on an application where I needed a method to return two separate values. I turned to good ole output parameters. I know I could have created two separate methods but the values within the problem domain are always associated. Therefore, it made sense to me to use output parameters with one method.

Here is an example using a NUnit test and the method returning two values via output parameters.

public void TestParseAndReturnTwoSeperateStrings()
string toParse = "00050000999";
string strOne;
string strTwo;

ParseAndReturnTwoSeperateStrings (toParse, out strOne, out strTwo);

Console.WriteLine("String 1: {0}", strOne);
Console.WriteLine("String 2: {0}", strTwo);

Assert.AreEqual("000", strOne);
Assert.AreEqual("50000999", strTwo);

private void ParseAndReturnTwoSeperateStrings (string input,
out string strOne, out string strTwo)
strOne = input.Substring(0, 3);
strTwo = input.Substring(3, input.Length - 3);

No comments: