I read the C++ version of this question but didn't really understand it.
Can someone please explain clearly if it can be done and how?
I read the C++ version of this question but didn't really understand it.
Can someone please explain clearly if it can be done and how?
Mainly two methods are there. 1. Use out/ref parameters 2. Return an Array of objects
Just use in OOP manner a class like this:
The function member returns the quotient which most callers are primarily interested in. Additionally it stores the remainder as a data member, which is easily accessible by the caller afterwards.
This way you can have many additional "return values", very useful if you implement database or networking calls, where lots of error messages may be needed but only in case an error occurs.
I entered this solution also in the C++ question that OP is referring to.
Classes, Structures, Collections and Arrays can contain multiple values. Output and reference parameters can also be set in a function. Return multiple values is possible in dynamic and functional languages by means of tuples, but not in C#.
Here are basic
Two
methods:1) Use of '
out
' as parameter You can use 'out' for both 4.0 and minor versions too.Example of 'out':
Output:
Area of Rectangle is 20
Perimeter of Rectangle is 18
*Note:*The
out
-keyword describes parameters whose actual variable locations are copied onto the stack of the called method, where those same locations can be rewritten. This means that the calling method will access the changed parameter.2)
Tuple<T>
Example of Tuple:
Returning Multiple DataType values using
Tuple<T>
Output
NOTE: Use of Tuple is valid from Framework 4.0 and above.
Tuple
type is aclass
. It will be allocated in a separate location on the managed heap in memory. Once you create theTuple
, you cannot change the values of itsfields
. This makes theTuple
more like astruct
.A method taking a delegate can provide multiple values to the caller. This borrows from my answer here and uses a little bit from Hadas's accepted answer.
Callers provide a lambda (or a named function) and intellisense helps by copying the variable names from the delegate.
You either return a class instance or use out parameters. Here's an example of out parameters:
Call it like this: