As per title is there any difference passing a reference type to a method such as:
public void GetStream(Stream outputStream)
{
outputStream.Write(data);
}
VS
public Stream GetStream()
{
MemoryStream ms = new MemoryStream();
ms.Write(data);
return ms;
}
I noticed alot of Java code passes class by reference (not sure of the exact reasons for this). However in .NET is this just a matter of preference?
When would you choose one over the other?
The two are very different. In your first example, the caller is responsible for creating a stream (of whatever kind they prefer), and may pass a stream that is already positioned at some arbitrary position.
In the second, the callee has determined the type of stream, and is always writing at position 0.
If your first example was instead:
they would at least be closer to comparable.
Here, the major difference is that the caller has to have a declared variable to capture the
outputStream, whereas in the other case, the caller could ignore the returned stream value.However, the second from (returning the value) is more commonly seen – if a method has a single value to return, it’s by far preferred that that value is returned by the method, rather than a
voidmethod with anoutparameter – mostly, in .NET,outparameters should be used sparingly (and only if the return value from the method is already something useful). An example of such a method would be theTryParsemethods on various types, that return abool(indicating success), and the parsed value is passed back as anoutparameter.