Friday, 23 June 2017

Ref - Out and ParamsArray Examples in Csharp

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

namespace RefOutParamsArrayConsoleApp17
{
    class Program
    {
        static void Main(string[] args)
        {
            int start = 0;          
            Console.WriteLine("Pass by Val method below");
            Program.PassByValueMethod(start);
            Console.WriteLine(start);
            Console.WriteLine("Pass by Ref method below");
            Program.PassByRefMethod(ref start);
            Console.WriteLine(start);

            int totAdd = 10;
            int totProd = 30;
            Console.WriteLine("Pass by  Out MultiResultReturn method below");
            Program.MultiResultReturn(totAdd, totProd, out totAdd, out totProd);
            Console.WriteLine("total sum is {0} && total product is {1}",totAdd ,totProd);

            Console.WriteLine("Pass by Array(as parameter) method below");
            int[] Numberss = new int[3];
            Numberss[0] = 101;
            Numberss[1] = 102;
            Numberss[2] = 103;
            PassByArrayMethod(1, 2, 3);
            Console.WriteLine();
            Program.PassByArrayMethod(Numberss);
            Console.ReadKey();
        }
        public static void PassByValueMethod(int j)
        {
            j = 100;
        }

        public static void PassByRefMethod(ref int k)
        {
            k = 200;
        }

        public static void MultiResultReturn(int FN, int SN, out int sum, out int product)
        {
            sum = FN + SN;
            product = FN * SN;
        }

        public static void PassByArrayMethod(params int[] Numbers)
        {
            foreach (int i in Numbers)
            {
                Console.WriteLine(i);
            }
        }
    }
}
Output :