Sunday 4 December 2016

C# ReferenceType: PassByVal & PassByRef

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

namespace App5
{
classProgram
    {
staticvoid Main(string[] args)
        {
int[] a = { 1, 3, 4, 6 };

Console.WriteLine("array before pass by ref");
foreach (int x in a)
Console.WriteLine(x);

PassByRef(a);
Console.WriteLine("array after pass by ref");
foreach (int x in a)
Console.WriteLine(x);

PassByVal(a);
Console.WriteLine("array after pass by VAL");
foreach (int x in a)
Console.WriteLine(x);
Console.ReadLine();
        }
staticvoidPassByRef(int[] a)
        {
for (int i = 0; i <a.Length; i++)
            {
a[i] = a[i] + 1;
            }
        }
staticvoidPassByVal(int[] a)
        {
            a = newint [3]{ 0, 0, 0};
Console.WriteLine("array in pass by VAL");
foreach (int x in a)
Console.WriteLine(x);
        }
   }
}

OUTPUT:



        array before pass by ref

        1

        2

        3

        4

        6

        array after pass by ref

        2

        4

        5

        7

        array in pass by VAL

        0

        0

        0

        array after pass by VAL

        2

        4

        5

        7

No comments:

Post a Comment