C# method parameters

Description

A method has a sequence of parameters. Parameters define the set of arguments that must be provided for that method.

The following code defines a method called add, which adds two int type variables together.

add method has two parameters, a and b. When calling the add method we must provide data for a and b.


using System;/*  www . j  a v a 2  s  .  com*/

class Program
{
    static int add(int a, int b)
    {
        int result = a + b;
        Console.WriteLine(result);
        return result;
    }

    static void Main(string[] args)
    {
        add(1, 2);
    }
}

In general, parameters can be passed into methods by reference or by value.

The code above generates the following result.

Pass-by-value versus pass-by-reference

When a variable is passed by reference, the called method gets the actual variable. Any changes made to the variable inside the method persist when the method exits.

When a variable is passed by value, the called method gets a copy of the variable. Any changes made are lost when the method exits.

Note

In C#, all parameters are passed by value unless you specifically say otherwise. We have to understand the implications for reference types.

Reference type variables hold only a reference to an object, it is this reference that will be copied, not the object itself. Hence, changes made to the underlying object will persist.

Value type variables, in contrast, hold the actual data, so a copy of the data itself will be passed into the method.

Example

An int is passed by value to a method, and any changes that the method makes do not change the value of the original int object.

If an array or any other reference type, such as a class, is passed into a method, and the method uses the reference to change a value in that array, the new value is reflected in the original array object.


using System; //from   w w  w .j  av a  2  s. c o m
                   
class MainClass
{ 
   static void SomeFunction(int[] ints, int i) 
    { 
       ints[0] = 100; 
       i = 100; 
    } 
    public static int Main() 
    { 
       int i = 0; 
       int[] ints = { 0, 1, 2, 4, 8 }; 

       SomeFunction(ints, i); 
       Console.WriteLine("i = " + i); 
       Console.WriteLine("ints[0] = " + ints[0]); 
       return 0; 
    } 
}  

Notice how the value of i remains unchanged, but the value changed in ints is also changed in the original array.

The code above generates the following result.

Note 2

You can control how parameters are passed with the ref and out modifiers:

Parameter modifierPassed byVariable must be definitely assigned
NoneValueGoing in
refReferenceGoing in
outReferenceGoing out




















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor