I want to define a function with two outputs. The first one is a boolean variable and the second one is 2D array with unknown numbers of rows and columns but the array will be defined if the boolean variable is true and if the boolean variable is false, the array is not defined. how can I define this function? I am thankful if anybody can exemplify it in an example. Thanks
Asked
Active
Viewed 1,376 times
-6
-
3Can you just return a `Tuple
`? Or make your own class and return containing both and return an instance of that. – Equalsk Apr 03 '17 at 12:04 -
Either return an object which is a composite of the two or use an output parameter. – David Apr 03 '17 at 12:04
-
4Why not just return `null` instead of false ? – mrogal.ski Apr 03 '17 at 12:06
-
Also you need to have a compelling reason for using arrays instead of a better collection type. – rory.ap Apr 03 '17 at 12:08
-
out variable will be very much helpful for u. just declare 2d array variable as out int arr[] anr return boolean variable return true; out variable will return u array and return true or false will return u boolean result. For ex: public void func1(out int arr[]) { //your code here return boolVariable; } – Pravin Durugkar Apr 03 '17 at 12:10
2 Answers
0
You want something like this .
Tuple<string, int> NameAndId()
{
// This method returns multiple values.
return new Tuple<string, int>("Test", 100);
}

G.Mich
- 1,607
- 2
- 24
- 42
0
Why not return null
if array is not defined?
public static bool MyMethod(out int[,] array) {
array = null;
...
}
....
int[,] data;
if (MyMethod(out data)) {
....
}
Or in case of C# 7.0+
if (MyMethod(out var data)) {
....
}
Edit: if you want to return an array, but you don't know its Length
(or want to adjust it) you can try working with List<T>
and put .ToArray()
in the end:
using System.Linq;
...
List<int> list = new List<int>();
list.Add(1);
list.Add(5);
list.Add(10);
...
list.Remove(5);
...
list.RemoveAt(0);
...
array = list.ToArray();

Dmitry Bychenko
- 180,369
- 20
- 160
- 215
-
Thanks. Can I know how I should return the array with unknown size? For each iteration of my algorithm, the size of the array will change. I am thankful if you can exemplify it. – Amin Apr 04 '17 at 07:55