Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>What are you doing in your method? If you're merely populating an existing array, then you don't need pass-by-reference semantics - either in .NET or in Java. In both cases, the reference will be passed by value - so changes to the <em>object</em> will be visible by the caller. That's like telling someone the address of your house and asking them to deliver something to it - no problem.</p> <p>If you <em>really</em> want pass-by-reference semantics, i.e. the caller will see any changes made to the parameter itself, e.g. setting it to null or a reference to a different byte array, then either method needs to return the new value, or you need to pass a reference to some sort of "holder" which contains a reference to the byte array, and which can have the (possibly changed) reference grabbed from it later.</p> <p>In other words, if your method looks likes this:</p> <pre><code>public void doSomething(byte[] data) { for (int i=0; i &lt; data.length; i++) { data[i] = (byte) i; } } </code></pre> <p>then you're fine. If your method looks like this:</p> <pre><code>public void createArray(byte[] data, int length) { // Eek! Change to parameter won't get seen by caller data = new byte[length]; for (int i=0; i &lt; data.length; i++) { data[i] = (byte) i; } } </code></pre> <p>then you need to change it to either:</p> <pre><code>public byte[] createArray(int length) { byte[] data = new byte[length]; for (int i=0; i &lt; data.length; i++) { data[i] = (byte) i; } return data; } </code></pre> <p>or:</p> <pre><code>public class Holder&lt;T&gt; { public T value; // Use a property in real code! } public void createArray(Holder&lt;byte[]&gt; holder, int length) { holder.value = new byte[length]; for (int i=0; i &lt; length; i++) { holder.value[i] = (byte) i; } } </code></pre> <p>For more details, read <a href="http://pobox.com/~skeet/csharp/parameters.html" rel="noreferrer">Parameter passing in C#</a> and <a href="http://pobox.com/~skeet/java/parameters.html" rel="noreferrer">Parameter passing in Java</a>. (The former is better written than the latter, I'm afraid. One day I'll get round to doing an update.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload