Home > DeveloperSection > Forums > What is the difference between ref & out parameters.
Ankit Singh

Total Post:341

Points:2389
Posted on    November-15-2015 10:00 PM

 .NET C# 
Ratings:


 1 Reply(s)
 270  View(s)
Rate this:
i want know difference between ref & out parameters please explain it.


aditya kumar Patel

Total Post:250

Points:1782
Supported
Posted on    November-15-2015 10:25 PM

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

}

}

}


Don't want to miss updates? Please click the below button!

Follow MindStick