Functional side effects occur when functions
- modify a global variable, or
- modify one of its parameters
Modifying one of its parameters
Mutations made by the function will persist only if the parameters are passed by reference, which can be achieved using either the keyword ref
or out
.
For example,
int fun1(ref int num)
{
num = 100;
return 10;
}
void main()
{
int a = 2;
a = fun1(ref a) + a;
Console.WriteLine(a);
}
The output will be 110
However, the variable will not be modified if there is no ref
or out
keyword:
int fun1(int num)
{
num = 100;
return 10;
}
void main()
{
int a = 2;
a = fun1(a) + a;
Console.WriteLine(a);
}
The result will be 12
The difference between ref
and out
is that ref
parameter must be initialized before it is passed; while out
parameter do not have to be explicitly initialized before they are passed (Docs, 2018).
References
- Docs, M. (2018, March 6). ref (C# Reference). Retrieved from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref