What is the difference between “out” and “ref” in C#?
Before diving into the differences, check the link if you don’t know what “ref” does in c# in detail? > here
To use ref and out we will deal with the functions which will be invoked inside the Main function. In a standard case, when we send a parameter to function and do some changes on the value inside the function, it does not affect the value of the variable which is declared inside the Main function. Because there is no reference here. They are just value types. In other words: By default, parameters are passed to a method by value. By using these keywords (ref and out) we can pass a parameter by reference. If you want the changes to affect the value of the variable which you’ve declared inside the Main, you will have to use ref or out. If you use ref, you don’t need to initialize the variable inside the function(but you can, it is up to you), but if you use out you will have to initialize the variable inside the function. Let’s see some examples to make sure we have enclosed everything well.
Here is a code snippet in which we’re going to use the “ref”
class Program{public int Funk(ref int num){num = num* num;return num;}static void Main(string [] args){int num = 4;Console.WriteLine($"The value of the num before calling the function {num}");Program pr = new Program();pr.Funk(ref num);Console.WriteLine($"The value of the num before calling the function {num}");
}}
As you see above, we have not initialized the value of num inside the Funk function. The result :
Let’s just change ref to out :
As you see, here we get an error which is shown by means of the red underline below the num. The error appears as we have not initialized a value to num inside of the function, although we have used “out”. So, to solve the problem, we only will have to give a value to the num inside Funk.
So, everything is okay now. Let’s see the result.
See you soon.