A function does not return an array [duplicate]

Why my first idea didn’t work

Because it’s a syntax error…

If you want array shorthand like that you need to use VB. The shortest it gets in C# is, I believe:

static public int[] FunctionThatReturnsAVector(){
    return new[]{0, 0, 0, 0};   
}

I should point out that this works because the method declares a return type of int[] and new[]{0,0,0,0} creates an int array because the compiler treats the 0 as ints for the type inference it performs.

If you had written:

static public long[] FunctionThatReturnsAVector(){

You would need to match the value types up of at least one item so that the compiler infers long[]

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

One item is a long and the other ints can be expanded to a long

whereas the second one – does?

The second one is a supported syntax of initing an array, the type for which is declared to the compiler on the left

Had you written :

var result = {0, 0, 0, 0};

You would be back to a syntax error.

You might be thinking “but why can’t the compiler look at my first way and get the return type from the method, and see it’s return, and infer that must be an init’r for an array of int, and just.. do it?

If you really want that shorthand, you’ll have to ask for it to be implemented; the teams that write c# and the compiler are reachable on github.. https://github.com/dotnet/roslyn https://github.com/dotnet/csharplang

Leave a Comment