Wednesday, July 11, 2007

Passing Parameters

The int and the string default to being passed by value while the array and the object default to being passed by reference. I thought strings were reference types and arrays of chars!

If the below is modified by adding the "ref" key-word at the front of each argument and parameter; they all get passed by reference.

[C#]

// ----------------------------------------------
// From: http://coding-help.blogspot.com/
// Title: Passing Parameters
// Date: 11 July 2007
// Author: R. K. Wijayaratne
// Description: Tests how different types
// get passed as parameters.
//
// To Run: Create a new C# file, e.g. "Program.cs",
// copy and paste the code below into it and save.
// To compile it open the .NET Framework command
// prompt and type:
//
// csc C:\MyPath\Program.cs
//
// where "C:\MyPath\" is the path of the C# file.
// If there are any errors correct them. To run
// the program type "Program" and press "Enter."
// ----------------------------------------------

using System;

public class SomeObject
{
  public string ValueA;
  public int ValueB;
}

public class Tester
{
  // Program entry point.
  static void Main(string[] args)
  {
    // Start running the test.
    Tester.StartTest();
  }

  // Test driver method.
  public static void StartTest()
  {
    // Initialize values.
    int someInt = 1;
    string someString = "1";
    char[] charArr = new char[] { '1' };
    SomeObject someObj = new SomeObject();
    someObj.ValueA = "1";
    someObj.ValueB = 1;

    // Call to modify values.
    TestHelper.TestPassByRef(someInt,
    someString, charArr, someObj);

    // Output changes to console.
    Console.Write("someInt: {0}\nsomeString: {1}\n"
    + "charArr[0]: {2}\nsomeObj.ValueA: {3}\n"
    + "someObj.ValueB: {4}\n", someInt,
    someString, charArr[0], someObj.ValueA,
    someObj.ValueB);
  }
}

public class TestHelper
{
  public static void TestPassByRef(int someInt,
  string someString, char[] charArr,
  SomeObject someObj)
  {
    // Modify values.
    someInt = 2;
    someString = "2";
    charArr[0] = '2';
    someObj.ValueA = "2";
    someObj.ValueB = 2;
  }
}

Console Output

someInt: 1
someString: 1
charArr[0]: 2
someObj.ValueA: 2
someObj.ValueB: 2


Also See

  1. See 'C# Programmer's Reference: Passing Parameters' here http://msdn2.microsoft.com/en-us/library/0f66670z(vs.71).aspx

  2. See 'Parameter passing in C#' here http://www.yoda.arachsys.com/csharp/parameters.html

  3. See 'Parameter passing in C#' here http://rapidapplicationdevelopment.blogspot.com/2007/01/parameter-passing-in-c.html

No comments: