-3

I am trying to learn C# via Unity, and I was wondering does C# have the same semantics as Java when it comes to pass-by-reference or pass-by-value for parameters and return values?

I see in the C# language that you can use ref to indicate something is pass by reference, does that mean it is pass by value by default?

Java being pass by reference by default unless it is a primitive type (i.e. something that does not extend from Object)

That includes arrays in Java. But I am not sure about C#.

Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265
  • Related: [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?rq=1) – Slaw Jun 22 '19 at 01:51

1 Answers1

5

Java is always pass-by-value, for both primitive types and non-primitive types.

e.g.,

void JavaMethod(int i, Foo f)
{
    i = 9; //not changed from caller's point of view
    f = new Foo(); //not changed from caller's point of view
}

C# is pass-by-value unless the 'ref' keyword is used:

void CSharpMethod(int i, Foo f, ref int j, ref Bar b)
{
    i = 9; //not changed from caller's point of view
    f = new Foo(); //not changed from caller's point of view

    j = 9; //changed from caller's point of view
    b = new Bar(); //changed from caller's point of view
}

In both languages, you can modify the internal state of an non-primitive object when it is passed by value:

void JavaOrCSharpMethod(Foo f)
{
    f.field = 9; //internal state is changed from caller's point of view
}

Keep in mind the difference between assigning a new instance to a parameter and modifying the internal state of the object. Not understanding this is the source of a lot of confusion about this subject.

Also, there is no real substance in whether a primitive type or non-primitive type is used, other than the fact that primitive types do not have members which change their state, so it's always done via assignment. Any non-primitive type where state can only be changed via assignment would seem the same.

I would include some C++ examples also, but this would drastically complicate the discussion since C++ has many ways of implementing pass-by-reference.

Dave Doknjas
  • 6,394
  • 1
  • 15
  • 28