The best way to understand that difference is to show it in code.
Let’s say we have an ‘Add’ function. And the only thing that method does is add 10 to the parameter value.
static void Main (string[] args) { int myParameter = 20; Add(myParameter); Console.WriteLine(myParameter); } static void Add(int myParameter) { myParameter = myParameter + 10; }
What happens if that code works?
static void Main (string[] args) { int myParameter = 20; //myParameter = 20; Add(myParameter); //myParameter is sent to function and there a new copy of this value manipulated to 30 (20 + 10) Console.WriteLine(myParameter); //myParameter = 20 (Add function did not change the value of myParameter in the main.) }
Now it is time to use “ref“:
static void Main (string[] args) { int myParameter = 20; Add(myParameter); Console.WriteLine(ref myParameter); } static void Add(ref int myParameter) { myParameter = myParameter + 10; }
What happens if that code works?
static void Main (string[] args) { int myParameter = 20; //myParameter = 20; Add(myParameter); //myParameter is sent to function and its refence value updated to 30 (20 + 10) Console.WriteLine(myParameter); //myParameter = 30 (Add function updated the value of myParameter in the main.) }
And finally, let’s use “out“:
static void Main (string[] args) { int myParameter = 20; Add(myParameter); Console.WriteLine(out myParameter); } static void Add(out int myParameter) { myParameter = 0; //We have to initialize the out parameter inside the function. myParameter = myParameter + 10; }
What happens if that code works?
static void Main (string[] args) { int myParameter = 20; //myParameter = 20; Add(myParameter); //myParameter is sent to function and its refence value updated to 10 (0 + 10) Console.WriteLine(myParameter); //myParameter = 10 (Add function updated the value of myParameter in the main. But this time the value we sent in the main is ignored.) }
So here are the main differences between ref and out:
– You have to initialize your ref parameter before sending. But you don’t have to do that for out parameter.
– You have to initialize your out parameter in the function you sent. But you don’t have to do that for ref parameter.