Click here to Skip to main content
15,906,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
why output parameters are used rather than return value.

what are the advantages of output parameters.what is the difference b/w input and

outputparameters

What I have tried:

why output parameters are used rather than return value.

what are the advantages of output parameters.what is the difference input and outputparameters
Posted
Updated 1-Aug-16 8:29am
v2
Comments
Philippe Mori 1-Aug-16 22:07pm    
You wrote almost the same thing twice... or even 3 time if we consider the title.

1 solution

An return value can return only one object - and while that can be a class instance containing other class instances, it still means you can only return one object - so if you want to return multiple values you either have to create a "container" class specifically to hold the data you want to return to the calling method, or you need to use out or ref parameters.
For example, suppose you create a method which sets up a File Open dialog and lets the user select a file for you. The problem is that you want to know if the user pressed cancel...so now you have two items you need to return: the file name and a bool which says "user selected this file". To do that, you need to return two distinct values, so you could create a container class:
C#
public class FileReturn
   {
   public string FileName;
   public bool IsSelected;
   }
...
public FileReturn SelectAFile()
   {
   FileReturn result = new FileReturn();
   ...
   result.FileName = myOpenFileDialog.FileName;
   result.IsSelected = true;
   return result;
   }
But that is cumbersome to use:
C#
string fileName;
FileReturn fr = SelectAFile();
if (fr.IsSelected)
   {
   fileName = fr.FileName;
   ...

Instead, you can use an out parameter to return the filename:
C#
public bool SelectAFile(out fileName)
   {
   ...
   fileName =  myOpenFileDialog.FileName;
   return true;
   }
Then it's cleaner to use:
C#
string fileName;
if (SelectAFile(out fileName))
   {
   ...
 
Share this answer
 
Comments
BillWoodruff 2-Aug-16 1:56am    
+5 perfect.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900