WHAT IS THE DIFFERENCE BETWEEN REF & OUT PARAMETERS.

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
C# 
 523  View(s)
Ratings:
Rate this:
i want know difference between ref & out parameters please explain it.
  1. aditya kumar Patel

    Post:254

    Points:1810
    Re: What is the difference between ref & out parameters.

    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

    }

    }

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!