[Solved] How to return an array literal in 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?

Enquirer: sgarg


Solution #1:

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 };
Respondent: Blorgbeard

Solution #2:

Blorgbeard is correct, but you also might think about using the new for .NET 4.0 Tuple class. I found it’s easier to work with when you have a set number of items to return. As in if you always need to return 3 items in your array, a 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);
Respondent: jb.

Solution #3:

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

return new int[3];
Respondent: anouar.bagari

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.