what I want to do is really basic, I think. To code example shows it clearly.
class MyClass{
public string[] Bar;
}
MyClass Foo = new MyClass();
Foo.Bar = { "word", "word", "word" };
This code gives me an error in Visual Studio C#. (Only assignment, call, increment, decrement, and new object expressions can be used as a statement)
Is there a better way to provide an array to the class? The array could be const for my part.
How can I provide an (const) array to a class from outside?
I don’t want to use the constructor, because the array should be optionally.
You can only initialize arrays using the
{}without thenewoperator as part of a declaration (which in turn has to explicitly specify the array type). This has nothing to do with whether it’s in the same class or not:See sections 12.6 (array initializers), 10.5 (field declarations), 8.5.1 (local variable declarations) and 7.6.10.4 (array creation expressions) of the C# 4 specification for details.
To answer your comment on Darin’s post: no, there’s no such thing as a “const” array in any sense I can imagine you mean. Even if you make the array variable readonly, like this:
that only makes the variable read-only.
Valueswill always refer to the same array object (which will therefore always have 3 elements) but arrays themselves are always mutable. If you want to build a read-only collection, I’d suggest usingReadOnlyCollection<T>, probably via List.AsReadOnly():