Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java and C# pass by value differences

Tags:

java

c#

I think the code below will make my question clear. If they both pass by value, why are they different.

C# below:

static void Main(string[] args)
    {
        var list = new List<int> {1, 2, 3,};
        ChangeVars(list);
        foreach (var i in list)
        {
            Console.WriteLine(i);
        }
        Console.Read();
    }

    private static void ChangeVars(List<int> list)
    {
        for(int i = 0; i < list.Count; i++)
        {
            list[i] = 23;
        }
    }

Returns 23, 23, 23,

Java below:

public static void main(String[] args)
{
    List<Integer> goods = new ArrayList<Integer>();
    goods.add(1); goods.add(2); goods.add(3);
    ChangeThings(goods);

    for(int item: goods)
    {
        System.out.println(item);
    }
}

private static void ChangeThings(List<Integer> goods)
{
    for(int item: goods)
    {
        item = 23;
    }
}

Returns 1, 2, 3.

I don't understand the discrepancy.

like image 204
Robert McB Avatar asked Sep 18 '26 18:09

Robert McB


2 Answers

You're seeing the difference between a foreach loop and a regular for loop.
Your Java code only assigns the local item variable; it doesn't actually modify the list.

If you write goods.set(i, 23), you will modify the list.

like image 83
SLaks Avatar answered Sep 21 '26 08:09

SLaks


The "discrepancy" has nothing to do with passing by value. You are using a different kind of loop in Java, the one where the list is not modified. That's why you see the difference.

If you replace the Java loop with a for (int i = 0 ... ) kind or replace the C# loop with a foreach, there would be no differences between the two programs. In fact, C# program will not compile, because assigning the loop variable is a very common error:

    foreach(int item in list)
    {
        item = 23; // <<=== This will not compile in C#
    }
like image 33
Sergey Kalinichenko Avatar answered Sep 21 '26 09:09

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!