In this system we will discuss on
Different types of method parameters
Method Parameters Vs Method Arguments
Types of method parameters:
1.value parameters:
creates a copy of paramter passed,so modification does not affect each other.
i -------------------------------------> 10
j -------------------------------------->10
i and j pointing to different memory locations.Operations one variable will not effect on other variable value.
Example:
using System;
namespace arrays {
class Program {
static void Main(string[] args) {
int a = 0;
Add(a);
Console.WriteLine(a);
}
public static void Add(int a) {
a = 100;
}
}
}
2.reference parameters:
The ref method parameter keyword on a method parameter causes a method to refer to the same variable that was passed into the method .Any change made to the parameter in the method will be reflected in that variable when control passes back to the calling method.
I and j are pointing to the same memory location.Operations one variable will effect on other variable value.
Example :
using System;
namespace arrays {
class Program {
static void Main(string[] args) {
int a = 0;
Add(ref a);
Console.WriteLine(a);
Console.ReadLine();
}
public static void Add(ref int a) {
a = 100;
}
}
}
3.out parameters:
use when you want a method to returns more than one value.
Example :
using System;
namespace arrays {
class Program {
static void Main(string[] args) {
int sum = 0, product = 0;
Add(10, 20, out sum, out product);
Console.WriteLine("sum {0},product {1}", sum, product);
}
public static void Add(int a, int b, out int sum, out int product) {
sum = a + b;
product = a * b;
}
}
}
4.parameter arrays:
The params kewyord lets you spwcify a method parameter that takes a variable parameter arraysnumber of arguments.You can send a comma separated list of arguments,or an array,or no arguments.
params keyword should be the last one in a method declaration and only one params keyword is permitted in a method declaration.
Example:
using System;
namespace arrays {
class Program {
static void Main(string[] args) {
int[] array = new int[3];
array[0] = 1;
array[1] = 2;
array[2] = 3;
Add(4, 5, 6);
}
public static void Add(params int[] array) {
foreach(int i in array) {
Console.WriteLine(i);
}
}
}
}
Method parameters Vs Method arguments:
A parameter represents a value that the procedure expects you to pass when you call it.
An argument represents the value that you pass to a procedure parameter when you call the procedure.
Example:
using System;
namespace arrays
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[3];
array[0] = 1;
array[1] = 2;
array[2] = 3;
Add(4,5,6); // these are arguments
}
public static void Add(params int[] array){ //these are parameters
foreach (int i in array)
{
Console.WriteLine(i);
}
}
}
}