I have been making an effort on C# methods. There are three ways that parameters can be passed to a C# methods.
Value parameters : This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
Reference parameters : This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument.
Output parameters : This method helps in returning more than one value.
I understood above types of passing parameters with below sample codes.
using System;
namespace PassingParameterByReference
{
class MethodWithReferenceParameters
{
public void swap(ref int x)
{
int temp = 5;
x = temp;
}
static void Main(string[] args)
{
MethodWithReferenceParameters n = new MethodWithReferenceParameters();
/* local variable definition */
int a = 100;
Console.WriteLine("Before swap, value of a : {0}", a);
/* calling a function to swap the value*/
n.swap(ref a);
Console.WriteLine("After swap, value of a : {0}", a);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Before swap, value of a : 100
After swap, value of a : 5
With this codes i could understand to pass parameters to methods by reference. And then i examine below code to understand passing parameters to methods by output.
using System;
namespace PassingParameterByOutput
{
class MethodWithOutputParameters
{
public void swap(out int x)
{
int temp = 5;
x = temp;
}
static void Main(string[] args)
{
MethodWithOutputParameters n = new MethodWithOutputParameters();
/* local variable definition */
int a = 100;
Console.WriteLine("Before swap, value of a : {0}", a);
/* calling a function to swap the value */
n.swap(out a);
Console.WriteLine("After swap, value of a : {0}", a);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Before swap, value of a : 100
After swap, value of a : 5
These sample codes make same action with different ways. And i can't understand difference between two approaches.( Passing Parameters To Method By Output And By Reference). Two example's output is the same. What is this small difference?
Reference and Output parameters are very similar. The only difference is that
ref
parameters must be initialized.The compiler will actually view the
ref
andout
keywords the same. For example if you cannot have overloaded methods where the only difference is theref
andout
keywords.The following methods signatures will be viewed the same by the compiler, so this would not be a valid overload.