Though both ref and out parameters are used to pass the parameters by reference, they aren’t used in exactly the same way.
Ref
Ref keywords are used to pass an argument as a reference, meaning that when the value of that parameter changes in the called method, the new value is reflected in the calling method. An argument passed using the ref keyword must be defined in the calling method before getting passed to the called method.
Out
Out keywords is similar to ref keywords but they are different because the arguments passed using out keywords can be passed without any value to be assigned to it. An argument passed using the out keyword must be defined in the called method before being returning to the calling method.
Ref
Ref keywords are used to pass an argument as a reference, meaning that when the value of that parameter changes in the called method, the new value is reflected in the calling method. An argument passed using the ref keyword must be defined in the calling method before getting passed to the called method.
Out
Out keywords is similar to ref keywords but they are different because the arguments passed using out keywords can be passed without any value to be assigned to it. An argument passed using the out keyword must be defined in the called method before being returning to the calling method.
- public class Test {
- public static void Main() //calling method
- {
- int parameter1 = 1;
- int parameter2; // initialization optional.
- Function1(ref parameter1); // Passed parameter using ref
- Console.WriteLine(parameter1); // parameter1=2
- -
- Function2(out parameter2); // Passed parameter using out
- Console.WriteLine(parameter2); // parameter2=5
- }
- static void Function1(ref int value) //called method
- // so we can get parameter1's value here so so it will change parameter1 value to 1 after this method get called.
- {
- value++; //here we get 0 in value so value++ we get 2.
- }
- static void Function2(out int value)
- /*we can not get parameter2 value here, we have to initialize value to variable before returning from this method.*/
- {
- value = 5; //must be defined
- }
- }
- /* Output
- 2
- 5
- */
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.
Charwaka ThupiliPosted Nov 15, 2017, 2:20 AM
Hi, The code is wrong please correct and explain in a simple way