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?


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 };

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);

Solution 3:

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

return new int[3];