C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Next: We pass the local int val to each of these 3 methods and examine the results.
Int, uintExample 1: This code uses value-passing semantics. If it assigns the parameter, it only affects the local state of the method.
Example 2: This code uses ref. When this method sets its parameter to 2, this is reflected in the calling location (Main).
Example 3: This code uses out on its parameter. It sets its parameter to 3—this is reflected in the calling location.
C# program that demonstrates parameter passing
using System;
class Program
{
static void Main()
{
int val = 0;
Example1(val);
Console.WriteLine(val); // Still 0.
Example2(ref val);
Console.WriteLine(val); // Now 2.
Example3(out val);
Console.WriteLine(val); // Now 3.
}
static void Example1(int value)
{
value = 1;
}
static void Example2(ref int value)
{
value = 2;
}
static void Example3(out int value)
{
value = 3;
}
}
Output
0
2
3
Name: The name of the argument variables (if any) does not affect the behavior of the method.
Program 1: C#
using System;
class Program
{
static void Main()
{
// Argument = 5
// Argument = Sam
Perls(5, "Sam");
}
static void Perls(int id, string name)
{
Console.WriteLine(id);
Console.WriteLine(name);
}
}
Output
5
Sam
And: When the arguments are passed to the method, they are received as formal parameters.
Program 2: C#
using System;
class Program
{
static void Main()
{
Perls(5, "Sam");
}
static void Perls(int id, string name)
{
// Parameter = id
// Parameter = name
Console.WriteLine(id);
Console.WriteLine(name);
}
}
Output
5
Sam
Important: The compiler demands that an out parameter be "definitely assigned" before any exit. There is no such restriction with the ref.
Definite: When a method uses the out modifier, you can be sure that after you invoke it, your variable is definitely assigned.
And: This means you can write code that does not assign the variable before calling an out method.
Further: The compiler enforces rules on references. These avoid type safety issues and ensure your program doesn't do anything horrible.
Info: Formal parameters are important because their names do not matter. They are not affected by other names in the program.
So: Procedures become good black-box abstractions. We can modify and work on them independently of other parts of the program.
Review: Arguments are specific values passed to a method. Parameters are the variables where those values are received.
And: This disconnect provides a high level of abstraction, useful for developing complex yet understandable computer programs.