Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return code or out parameter?

I'm making a method to fetch a list of filenames from a server but I have come to a problem that I cannot answer.

The method returns two things:

  • an SftpResult which is an enum with a variety of return codes.
  • the list of filenames.

Of these three signatures:

public static ArrayList GetFileList(string directory, out SftpResult result)

public static SftpResult GetFileList(string directory, out ArrayList fileNames)

public static SftpFileListResult GetFileList(string directory)

(where SftpFileListResult is a composite object of an SftpResult and an ArrayList)

which is preferred and why?

like image 483
Nobody Avatar asked Sep 10 '10 12:09

Nobody


People also ask

What is the difference between return value and out parameter?

Generally, use an output parameter for anything that needs to be returned. When you want to return only one item with only an integer data type then it is better to use a return value. Generally, the return value is only to inform success or failure of the Stored Procedure.

Is return a parameter?

Return parameters are parameters that are available after the planning phase of a workflow. The values returned by these parameters are useful in debugging a workflow. You should understand how return parameters work and what parameters can be used as return parameters to debug workflows.

What is an out parameter?

The out parameter in C# is used to pass arguments to methods by reference. It differs from the ref keyword in that it does not require parameter variables to be initialized before they are passed to a method. The out keyword must be explicitly declared in the method's definition​ as well as in the calling method.

What is the difference between return value and out parameter sometime multiple value will be correct answers?

There is no real difference. Out parameters are in C# to allow method return more then one value, that's all.


1 Answers

Personally I prefer the last option (although using a List<T> or ReadOnlyCollection<T> instead of ArrayList). out parameters are basically a way of returning multiple values, and it's generally nicer to encapsulate those.

Another option in .NET 4 would be

Tuple<SftpResult, ArrayList> GetFileList(string directory)

That explicitly says, "this method returns two things... I've packed them together for you for this particular case, but it's not worth further encapsulating them: they're not worth composing in a separate type".

(If you're not using .NET 4 you could always write your own Tuple type.)

like image 161
Jon Skeet Avatar answered Oct 09 '22 00:10

Jon Skeet