How to return an array literal in C#
Asked Answered
A

3

104

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?

Anchovy answered 6/6, 2012 at 20:35 Comment(1)
It's also worth nothing that C# doesn't actually have array literals, but an array initialization syntax - to which the accepted answer refers. Literals are special in that they can be directly serialized, and can be assigned to const fields. This is not the case with array initialization syntax.Phocomelia
M
203

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 };
Molloy answered 6/6, 2012 at 20:36 Comment(4)
Woah ho, I didn't know you could implicitly type arrays! +1Vicechancellor
I found that new int [] {0,0,0} also works. It would be clearer in my opinion.Anchovy
@Anchovy That seems to be identical to the answer. And I disagree, implicit typing of the array means changing the constants to floating point would automatically get the correct array type.Djebel
Answer should include an important precision for beginners: this is not, in fact, a literal. Whenever this is called, a new array instance will be created and allocated.Frankly
P
12

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);
Pye answered 6/6, 2012 at 20:39 Comment(4)
If you have a variable number of items but want some extra functionality you can also do: return new List<int>(new int[]{0,0,0});Autocatalysis
@Autocatalysis wouldn't List<int>(Enumerable.Repeat(0, 3)) be better?Djebel
@Djebel It would be better if you wanted to vary the number of items, certainly.Autocatalysis
If you want a list with initial content you would be better using return new List<int> { 0, 0, 0 };. There is no need for the intermediary array.Kazim
G
10

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

return new int[3];
Glasswork answered 6/6, 2012 at 20:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.