Home > Interview Questions > C#.NET > In C# how many ways we can pass the parameters to a method?

In C# how many ways we can pass the parameters to a method?

by Webmaster   on 15/12/2016   Category: C#.NET   |  Level: Intermediate   |  Views: 144    |  Points: 25     |  Starter 


1. Value parameters - this value parameter used to copy the actual value of an argument into the formal parameter of the function. There is no effect on the argument if any changes in the parameter within the function.



static void Main(string[] args)
{
int i = 100;
Console.WriteLine("Main method, Value in i : {0}", i);
Change(i);
Console.WriteLine("Main method, after calling Change method : {0}", i);
Console.ReadLine();
}

static void Change(int i)
{
i = 10;
Console.WriteLine("Inside Change method, Value in i : {0}", i);
}


//Main method, Value in i : 100
//Inside Change method, Value in i : 10
//Main method, after calling Change method : 100


2. Reference parameters - this reference parameter copies the reference to the memory location of an argument into the formal parameter. There is an impact on the argument if any changes in the parameter within the function. No need to assign value in the ref parameter when passing into the function.


static void Main(string[] args)
{
int[] arrayNum = { 10, 20, 30 };
Console.WriteLine("Main method, First element in arrayNum : {0}", arrayNum[0]);
Change(ref arrayNum);
Console.WriteLine("Main method, after calling Change method : {0}", arrayNum[0]);
Console.ReadLine();
}

static void Change(ref int[] arrayNum)
{
arrayNum[0] = 40;
arrayNum = new int[5] { 100, 200, 300, 400, 500 };
Console.WriteLine("Inside Change method, First element in arrayNum : {0}", arrayNum[0]);
}

//Main method, First element in arrayNum : 10
//Inside Change method, First element in arrayNum : 100
//Main method, after calling Change method : 100



3.Output parameters - this output parameter used to returning more than one value from function. The out parameter must be assigned before passing into function.


static void Main(string[] args)
{
int i = 10;
Console.WriteLine("Main method, before calling Change method : {0}", i);
Change(out i);
Console.WriteLine("Main method, after calling Change method : {0}", i);
Console.ReadLine();
}

static void Change(out int i)
{
i = 20;
}
//Main method, before calling Change method : 10
//Main method, after calling Change method : 20




« What are the types of comments in C#?
» multiView
Post Question  |  Question Home

Recent Posts

User Responses


No response found, be the first to review this question.

Submit feedback about this code snippet

Please sign in to post feedback

Latest Posts