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:
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:
string fileName;
FileReturn fr = SelectAFile();
if (fr.IsSelected)
{
fileName = fr.FileName;
...
Instead, you can use an out parameter to return the filename:
public bool SelectAFile(out fileName)
{
...
fileName = myOpenFileDialog.FileName;
return true;
}
Then it's cleaner to use:
string fileName;
if (SelectAFile(out fileName))
{
...