1

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?

Glory Raj
  • 17,397
  • 27
  • 100
  • 203
Fixer
  • 5,985
  • 8
  • 40
  • 58

2 Answers2

2

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:

public void GetStream(out stream outputStream)
{
   outputStream = new MemoryStream();
   outputStream.Write(data);
}

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 void method with an out parameter - mostly, in .NET, out parameters 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 the TryParse methods on various types, that return a bool (indicating success), and the parsed value is passed back as an out parameter.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
1

First, the concept of "separation of concerns" suggests that a method called "GetStream" should not also write to the stream. Especially when "bytes" is not an incoming argument. This is really two separate functions, and should be coded that way.

But for the original question, passing by reference simply means that the method has the option of modifying an instance of an object. Using the return value to return a new, or existing, reference, is a step towards writing immutable objects, and is definitely worth considering as an implementation.

Cylon Cat
  • 7,111
  • 2
  • 25
  • 33