anonymous arrays

  • Thread starter Thread starter Paul E Collins
  • Start date Start date
P

Paul E Collins

This does what you'd expect ...

string[] foo = { "bar", "baz", "quux" };

.... so why is this a syntax error?

private string[] foo()
{
return { "bar", "baz", "quux" };
}

I know that it works with 'new string[]' inserted, but I don't understand
why assignment and 'return' disagree on what is a valid rvalue.

P.
 
Paul E Collins said:
This does what you'd expect ...

string[] foo = { "bar", "baz", "quux" };

... so why is this a syntax error?

private string[] foo()
{
return { "bar", "baz", "quux" };
}

I know that it works with 'new string[]' inserted, but I don't understand
why assignment and 'return' disagree on what is a valid rvalue.

It's not a normal expression - it's an array initializer, which may
only be specified in field declarations, local variable declarations
and array creation expressions.

I believe this is because all of those three know exactly what type
they should be constructing beforehand, whereas for general expressions
the type of the expression is not dependent on context.

I dare say it would have been possible to include this "exception" in
other places (such as return statements), but I suspect it would have
made the specification messier. Of course, they're not really *needed*
anywhere...
 
Back
Top