Passing parameters with modifiers in C#
Tags: csharp, dotnet
Published: 2019-10-02 23:42:14

A parameter is a variable that holds some sort of value that is passed as information into a function, procedure or method. Function, procedure, and method can be used as synonymous terms as they are named differently in different computer languages. (Guidelines, 2019)

If you do not want to change the value of the arguments you are passing into a method you will “pass by value”. This way the initial arguments passed into the method as it’s parameters will not have their values changed even if they are modified in the body of the method. If you want to change the value of the arguments you are passing into your method and have them persist within your working environment you will then have them “pass by reference”. 

There are several ways you can pass parameters in a method.

|Parameter Modifier|Passed By|Explicitly Assigned Before|Variables Changed Within |
| ------------------|:-------------:| -----:|---------:|
| None              |           Value|   Going In| Yes |
| ref               | Reference      | Going out | Yes |
| out               | Reference      | Going out | Yes |
| in                | Reference      | Going in  |   No|
| params            | Reference      | Going out | Yes |

When we say that the parameter is passed by the value we mean that a copy of that value is passed to the method. You can “pass by value” a value data type or a reference data type parameter and that parameter being passed will be an independent reference to the original value or reference type. (Albahari & Albahari, 2010) The copy that is being passed holds a different memory location than the original value.

It should be also noted that a parameter can be passed by reference or by value regardless of the parameter type, being value or reference. (Albahari & Albahari, 2006)

Don’t confuse passing by reference or passing by value with reference or value types. Below is a quick overview guide for value types and reference types. It is not a complete reference to all value and reference types but an overview to give a reminder and give context to the keywords we are using. (Wenzel, et al., 2019)

Value Type | Reference Type
-----------|---------------
bool | Class
byte | Interface
char | Delegate
decimal | Dymanic
double | Object
enum  | Array

___


## Passing a value into a method with no modifier

By default, in C# passing parameters through methods is done by value, which is the most common way of passing parameters in methods. (Albahari & Albahari, 2010)
 
### Default modifier

The initial value that we pass into the method will never have its original value changed, as shown below in the snippet of code.

```csharp
static void Main(string[] args)
{
    int items = 8; //items is asisgned 8
    itemsInStock(items);
    Console.WriteLine("Items to add to stock : {0}", items);
    //the variable items does not have its value changed
    Console.ReadLine();
}

static void itemsInStock(int items)
{
    int totalStock = 50;
    items = totalStock + items;
    Console.WriteLine("new items available in Stock : {0}", items);
    //items has its variable changed within the scope
}

```
Your output will be:

>New items available in Stock: 58
Items to add to stock : 8

___


### Passing values into a method with modifiers:

When you pass a parameter by reference it allows you to change the value of that passed parameter into the method while having it persist in the environment.

## Reference parameters: ref modifier

When using the ref modifier, it specifies that the parameter being passed into the method is being passed by reference and not by value. This means that the values passed in as a parameter with the ref modifier have the same corresponding memory location and their values, if changed, will persist in the scope outside of the method.

Before passing an argument with the ref modifier you must explicitly initialize it. The ref modifier is required both in writing and calling the method. (Data, 2001)

```csharp
static void Main(string[] args)
{
    int items = 8; //items is asisgned 8
    itemsInStock(ref items);
    Console.WriteLine("Items to add to stock : {0}", items);
    //the variable items has its value changed
    Console.ReadLine();
}

static void itemsInStock(ref int items)
{
    int totalStock = 50;
    items = totalStock + items;
    Console.WriteLine("new items available in Stock : {0}", items);
    //items has its variable changed within the scope
}

```
Your output will be:

>New items available in Stock: 58
Items to add to stock : 58

## Output parameter: out modifier

An out modifier is like a ref modifier in that it does not create a new storage location in memory for the passed argument. It is different from the ref modifier because you do not need to initialize the variable before it is passed. It also needs to be declared in the method definition and when calling the method.

The main purpose of using the out modifier is to be used when you have a need to have multiple return values. (Data, 2001)

```csharp
    static void Main(string[] args)
    {
        int items = 8; //items is assigned 8
        int apple, orange;
        itemsInStock(items, out apple, out orange);
        Console.WriteLine("Items to add to stock : {0}", items);
        //the variable items has its value changed
    
    Console.ReadLine();
    }

    static void itemsInStock(int items, out int apple, out int orange)
    {
        apple = 5;
        orange = 10;
        int totalStock = 50;
        items = totalStock + items;
        Console.WriteLine("New items available in Stock : {0}", items);
        //items has its variable changed within the scope
    }

```
Your output will be:

>New items available in Stock: 58
Items to add to stock : 8
We have 5 apples and 10 oranges.


## In parameters: in modifier

If you want to pass a parameter by reference read-only into a method with the intent of not copying the value but also not wanting to change the value you will need to use the in modifier. The only reason for using the in modifier would be for use in high-performance scenarios because passing an argument is constant and doesn’t depend on the size of the value. (Tepliakov, 2018) 

##Parameter array: params modifier

A parameter declared with a params modifier takes any variable number of arguments separated by commas or an array. You may also choose to specific no arguments which will result in the length of the params parameter list as 0. (Data, 2001) Its primary use is as a shorthand to input as many parameters you would like with no need to specify the use of an array.


### Conclusion

* A parameter passed by a ref modifier corresponds to the actual memory location of that value and if changed will persist outside the method scope/
* The out modifier should be used when you need to have multiple return values.
* The in modifier references the memory location of the parameter like the ref modifier but it will not allow the arguments passed to be changed. 
* The params modifier takes any number of parameters passed onto it separated by commas, an array or none. It is useful as shorthand and when you do not know the specificity of an array length.

___


###References
Albahari, J., & Albahari, B. (2006). *C# 4.0 IN A NUTSHELL The Definitive Reference.* Sebastopol: O'Reilly Media, Inc.

Albahari, J., & Albahari, B. (2010). *C# 4.0 Pocket Reference.* Sebastopol, CA, USA: O'Reilly Media. Retrieved October 1, 2019

Data, L. o.-i.-P. (2001). *Microsoft C# Language Specifications.* Redmond: Microsoft Press.

Guidelines, V. V. (2019, October 1). *Definitions of Words with Special Meanings.* Retrieved from U.S. Election Assistance Commission: [Online](https://web.archive.org/web/20121208084203/http://www.eac.gov/vvsg/glossary.aspx)

Tepliakov, S. (2018, March 7). *The ‘in’-modifier and the readonly structs in C#.* Retrieved from Microsoft Premier Developer: [Online](https://devblogs.microsoft.com/premier-developer/the-in-modifier-and-the-readonly-structs-in-c/)

Wenzel, M., Wagner, B., A, A., Latham, L., Schonning, N., Hoffman, M., & B, M. (2019, October 1). *Reference types (C# Reference).* Retrieved from Microsoft Documentation : [Online](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types)