Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an array literal in C#

Tags:

c#

I'm trying the following code. The line with the error is pointed out.

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

How can I return an array literal like string literals?

like image 975
sgarg Avatar asked Jun 06 '12 20:06

sgarg


People also ask

How can we return an array in C?

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.

Is array a literal in C?

Compound literals were introduced in C99 standard of C. Compound literals feature allows us to create unnamed objects with given list of initialized values. In the above example, an array is created without any name. Address of first element of array is assigned to pointer p.

Is an array a literal?

Array literalsAn array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ( [] ). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.


1 Answers

Return an array of int like this:

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

You can also implicitly type the array - the compiler will infer it should be int[] because it contains only int values:

return new [] { 0, 0, 0 }; 
like image 120
Blorgbeard Avatar answered Sep 28 '22 04:09

Blorgbeard