The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.
The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
namespace Forum
{
public class RefAndOut
{
static void Main(string[] args)
{
int refval = 0; //must be initialized
int outval; //optional
RefExample(ref refval);
Console.WriteLine(refval); // refval=1
OutExample(out outval);
Console.WriteLine(outval); // outval=2
Console.ReadLine();
}
static void RefExample(ref int value) //called method
{
value = 1;
}
static void OutExample(out int value) //called method
{
value = 2; //must be initialized
}
}
}
Liked By
Write Answer
What is the difference between ref & out parameters.
Join MindStick Community
You have need login or register for voting of answers or question.
Anonymous User
15-Nov-2015The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.
The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.