Understand this :
What's the difference between passing by reference vs. passing by value?
And Debug below code, you will get better idea.
static void Main(string[] args)
{
int num = 10;
MethodWithoutRef(num); //adding 2 in number [Pass by value]
Console.WriteLine(num); //still number at caller side not changed
//Output here : 10
Method(ref num); //adding 2 in number (here number is passed by ref)
Console.WriteLine(num); //number at caller side changed
//output here : 12
List<int> numList = new List<int>() { 10 };
//List is default passed by ref, so changes in method will be
// reflected at caller side even without using 'ref' keyword
MethodWithoutRef(numList); //[Pass by reference]
Console.WriteLine(numList[0]);
//output here : 12 and also, count of list has increased too
numList = new List<int>() { 10 };
//passing List with 'ref' doesnt make any differece in comparision with
// passing it without 'ref'
Method(ref numList);
Console.WriteLine(numList[0]);
//output here : 12 and also, count of list has increased too
numList = new List<int>() { 10 };
//passing List without ref in such method,
// where it creates new list out of it
MethodWithoutRefWithNewList(numList);
Console.WriteLine(numList[0]);
//output here : 10 and count of list is not changed
numList = new List<int>() { 10 };
//passing List without ref in such method,
// where it creates new list out of it
MethodWithNewList(ref numList);
Console.WriteLine(numList[0]);
//output here : 12 and count of list has increased too
}
while having these methods as different cases,
static void MethodWithoutRef(int num)
{
num = num + 2;
}
static void Method(ref int num)
{
num = num + 2;
}
static void MethodWithoutRef(List<int> numList)
{
numList[0] = numList[0] + 2;
numList.Add(12);
}
static void Method(ref List<int> numList)
{
numList[0] = numList[0] + 2;
numList.Add(12);
}
static void MethodWithoutRefWithNewList(List<int> numList)
{
numList = new List<int>(numList);
numList[0] = numList[0] + 2;
numList.Add(12);
}
static void MethodWithNewList(ref List<int> numList)
{
numList = new List<int>(numList);
numList[0] = numList[0] + 2;
numList.Add(12);
}
EDIT:
added an interesting point what Pranay has mentioned in his answer.