Showing posts with label ref in c# example. Show all posts
Showing posts with label ref in c# example. Show all posts

Monday, January 26, 2015

Ref Keyword in C#

By default when you pass argument to a method is value type. This means that change to the parameter that receives a value type will not affect the actual argument used in the call. But Through the use the ref, it is possible to pass any type of value as reference.

Before going into the mechanics of using ref, it is useful to understand why you might to pass a value type by reference reason is that

1.    It allows a method to alter the contents of its arguments.

Some time you will want a method to be able to operate on the actual arguments that are passed to it. Example: Swap() method that exchange the values of its two argument

Use of ref

The ref parameter modifier causes C# to create a call-by-reference, rather than a call-by-value. The ref modifier is specified when the method is declared and when it is called.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace use_ref
{
    class refdemo
    {
        public void sqr(ref int i)
        {
            i = i * i;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            refdemo obj = new refdemo();
            int a = 5;
            Console.WriteLine("a before call:" + a);
            obj.sqr(ref a);
            Console.WriteLine("a after call:" + a);
            Console.Read();
        }
    }
}


Note: Ref precedes the entire parameter declaration in the method and that is precedes the argument when the method is called.
Output of program



So using ref, it is now possible to write a method that exchanges the value of it two values of its two value-type arguments.

Example 2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace swap
{
    class valswap
    {
        public void swap(ref int a, ref int b)
        {
            int temp;
            temp = a;
            a = b;
            b = temp;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            valswap obj = new valswap();
            int x = 5;
            int y = 10;
            Console.WriteLine("x and y before call:" + x +" " + y);
            obj.swap(ref x, ref y);
            Console.WriteLine("x and y after call:" + x +" " + y);
          
        }
    }
}

Output of program


                                                              Author-Sayta Prakash