Friday, October 19, 2007

Method Parameters in C# (1)

Method Parameters in C#

There are four kinds of formal parameters:

  1. Value parameters, which are declared without any modifiers.
  2. Reference parameters, which are declared with the ref modifier.
  3. Output parameters, which are declared with the out modifier.
  4. Parameter arrays, which are declared with the params modifier.

1. Value parameters:

  • By default, the CLR assumes that all method parameters are passed by value.
  • A parameter declared with no modifiers is a value parameter.
  • A method is permitted to assign new values to a value parameter.
  • For value type instances, a copy of the instance is passed to the method. This means that the method gets its own private copy of the value type and the instance in the caller isn't affected.

2. Reference parameters:

  • A parameter declared with a ref modifier is a reference parameter.
  • Contrastingly to value parameter, a reference parameter does not make a new storage location. This means that the method can modify the object and the caller will see the change.
  • If a method's parameter is marked with ref, the caller must initialize the parameter's value prior to calling the method. The called method can read/write the value.

3. Output parameters:

  • A parameter declared with an out modifier is an output parameter.
  • Similar to a reference parameter, an output parameter does not create a new storage location. Instead, an output parameter represents the same storage location as the variable given as the argument in the method invocation.
  • Output parameters are typically used in methods that produce multiple return values.
  • If a method's parameter is marked with out, the caller isn't expected to have initialized the object prior to calling the method.
  • The called method can't read and must write to the value before returning.

blog comments powered by Disqus