101

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?

1
  • 6
    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.
    – cwharris
    Dec 9, 2016 at 21:40

3 Answers 3

197

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 };
4
  • 6
    Woah ho, I didn't know you could implicitly type arrays! +1 Jun 6, 2012 at 21:14
  • 1
    I found that new int [] {0,0,0} also works. It would be clearer in my opinion.
    – sgarg
    Mar 22, 2014 at 22:41
  • 3
    @sgarg 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.
    – NetMage
    Mar 10, 2017 at 16:59
  • 1
    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.
    – Crono
    Dec 16, 2022 at 13:04
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);
4
  • 2
    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});
    – Dave
    Dec 3, 2015 at 10:21
  • 1
    @Dave wouldn't List<int>(Enumerable.Repeat(0, 3)) be better?
    – NetMage
    Mar 10, 2017 at 19:05
  • @NetMage It would be better if you wanted to vary the number of items, certainly.
    – Dave
    Apr 12, 2017 at 10:13
  • 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.
    – Paul Ruane
    Oct 15, 2021 at 14:16
10

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

return new int[3];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.