How to return an array literal in C #

I am trying to use the following code. An error string is indicated.

int[] myfunction() { { //regular code } catch (Exception ex) { return {0,0,0}; //gives error } } 

How can I return an array literal as string literals?

+45
c #
Jun 06 2018-12-06T00:
source share
3 answers

Returns an int array as follows:

 return new int [] { 0, 0, 0 }; 

You can also implicitly enter an array - the compiler will conclude that it must be int[] , because it contains only int values:

 return new [] { 0, 0, 0 }; 
+94
Jun 06 2018-12-06T00:
source share

Blorgbeard is true, but you might also consider using the new .NET 4.0 Tuple. It was easier for me to work when you have a certain number of items to return. As in the case where you always need to return 3 elements in your array, the 3-int tuple makes it clear what it is.

 return new Tuple<int,int,int>(0,0,0); 

or simply

 return Tuple.Create(0,0,0); 
+11
Jun 06 2018-12-06T00:
source share

if the array has a fixed size and you want to return a new one filled with zeros

 return new int[3]; 
+5
Jun 06 2018-12-06T00:
source share



All Articles