Archive for May 2016

C#.NET ref and out parameters with example

ref stands for reference and out stands for output.

ref parameter variable should be initialized before we call the method. That value will be used a as reference value in the method.

out parameter variable initialization is not required but it should be returned by the method.

Example program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FirstConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            //val1 has to be initialized
            int val1 = 10;
            p.Add(ref val1);
            //val2 initialization not required
            int val2;
            int j = p.Sub(out val2);
            Console.WriteLine(j);
            Console.ReadKey();

        }

        public void Add(ref int val1)
        {            //code goes here
            Console.WriteLine("Hello");
        }
        public int Sub(out int val2)
        {
//val2 is changed from 2 to 5
            val2 = 5;
            return val2;
        }
    }
}

Output:
Hello
5


Tuesday, 31 May 2016
Posted by Sudhir Chekuri

Followers

Total Pageviews

Powered by Blogger.

- Copyright © 2013 DevStudent - Metrominimalist - Powered by Blogger - Designed by Johanes Djogan -