views:

733

answers:

4

Having the following class:

public class SomeClass
{
    private readonly int[] _someThings;

    public SomeClass()
    {
        _someThings = new int[4];
    }

    public int[] SomeThings
    {
        get { return _someThings; }
    }
}

How would I use the object initializer syntax to initialize the SomeThings property like in the following (non-working) code extract?

var anObject = new SomeClass
    {
        SomeThings[0] = 4,
        SomeThings[3] = 8
    }


Update

One could do (even without a set property):

anObject.SomeThings[0] = 4;
anObject.SomeThings[3] = 8;

But I'm trying to use the object initializer syntax.

+2  A: 

Object Initializer syntax is "syntatic sugar" for setting public properties.

There isn't a public setter for SomeThings, so you can't do it like this.

So, this...

Foo x = new Foo() { Bar = "cheese" };

... is the same as ...

Foo x = new Foo();
x.Bar = "cheese;

... and as such doesn't have any ability to reach into private members to set stuff.

Martin Peck
You're right, there is no public setter for SomeThings but it does not prevent someone from doing: anObject.SomeThings[0] = 4
Stecy
Nor should it. But it should prevent you from doing something like this: anObject.SomeThings = new int[5];
Chris Dunaway
+3  A: 

AFAIK, You could only have a Add method like this:

public class SomeClass
{
  void Add(int index, int item) 
  { 
    // ...
  }
}

var anObject = new SomeClass()
    {
        {0, 4}, // Calls Add(0, 4)
        {4, 8}  // Calls Add(4, 8)
    }
Stefan Steinegger
A: 

Theoretically you could do it this way:

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];
       }
   }
}
Jimmy
But you break encapsulation with this InitialSomeThings property setter. This setter should actually not exist.
Stefan Steinegger
A: 

You could 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});
Mitch Wheat
I know :)Maybe the example was a little too simplistic...I was merely trying a way to initialize a property returning an array.
Stecy