C # 3.0, object initializer and get returned property array, how to initialize?
Having the following class:
public class SomeClass
{
private readonly int[] _someThings;
public SomeClass()
{
_someThings = new int[4];
}
public int[] SomeThings
{
get { return _someThings; }
}
}
How do I use the object initializer syntax to initialize the SomeThings property like in the following (non-working) code extraction?
var anObject = new SomeClass
{
SomeThings[0] = 4,
SomeThings[3] = 8
}
Update
It would be possible (even without the set property):
anObject.SomeThings[0] = 4;
anObject.SomeThings[3] = 8;
But I am trying to use the object initializer syntax.
+1
a source to share
4 answers
In theory, you can do it like this:
var anObject = new SomeClass {
InitialSomeThings = new[] {
1,
2,
3,
4
}
}
class SomeClass {
private readonly int[] _somethings;
public int[]
get { return _somethings; }
}
public int[] InitialSomeThings {
set {
for(int i=0; i<value.Length; i++)
_somethings[i] = value[i];
}
}
}
0
a source to share
Object initializer syntax is syntactic sugar for setting public properties.
There is no public setter for SomeThings, so you cannot do it like this.
So this ...
Foo x = new Foo() { Bar = "cheese" };
... the same as ...
Foo x = new Foo();
x.Bar = "cheese;
... and as such is unable to contact private members to establish the material.
+2
a source to share
You can add an overloaded constructor:
public class SomeClass
{
private readonly int[] _someThings;
public SomeClass()
{
_someThings = new int[4];
}
public SomeClass(int[] someThings)
{
_someThings = someThings;
}
public int[] SomeThings
{
get { return _someThings; }
}
}
...
var anObject = new SomeClass(new [] {4, 8});
0
a source to share