Coffeehouse Post

Single Post Permalink

View Thread: object pass by value/reference
  • User profile image
    atehrani

    W3bbo,

       Your example is wrong. Take a look at this example (this time using primitives)

    public class PassByQuestion
    {
        public static void increment(int x)
        {
            x++;
        }
       
        public static void main(String[] args)
        {
            int i = 42;
            System.out.println(i);
            increment(i);
            System.out.println(i);
        }
    }

    Both outputs are 42, because it is pass-by-value.

    It is best demonstrated using C# (as it supports both pass-by-value and pass-by-reference).

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

    namespace Test
    {
        public class PassByQuestion
        {
            public static void increment_byvalue(int x)
            {
                x++;
            }

            public static void increment_byref(ref int x)
            {
                x++;
            }

            public static void Main()
            {
                int i = 42;
                Console.Out.WriteLine(i);
                increment_byvalue(i);
                Console.Out.WriteLine(i);
                increment_byref(ref i);
                Console.Out.WriteLine(i);
            }
        }
    }