Showing posts with label Ref vs Out in c#. Show all posts
Showing posts with label Ref vs Out in c#. Show all posts

Ref and Out

What is Ref and Out Keyword?

Ref and out keywords in C# are used to pass arguments within a method or function. Both indicate that an argument/parameter is passed by reference.

Ref

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.

Out

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.


Please find below example for more clarity.I have used both ref and out parameter and also describe how it's work. you can also find different between ref and out comparing codes.


  class Proram
    {
        public static void Main() //Calling Method
        {
            int refval=0;//Must be define value
            int outval; //No need to define value

            GetNumberByRef(ref refval);
            Console.WriteLine("Values after called method using ref is {0} ", refval);

            GetNumberByOut(out outval);
            Console.WriteLine("Value after called method using our is {0} ", outval);

            Console.ReadLine();
        }
        public static void GetNumberByRef(ref int value)//Called Method
        {
            value = 101;//here it's optional to define value
        }
        public static void GetNumberByOut(out int value)//Called Mathod
        {
            value = 101;//You must define value here
           
        }
    }

Output
 
Values after called method using ref  is 101
Value after called method using our is  101


Note: Out and ref cannot be used in method with async mathod.

Jagged Array

What is Jagged Array? Jagged array is called as "array of arrays". when you need a data inside your array element at that time you...