1

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.

4 Answers 4

3

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)
    }
Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

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

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];
       }
   }
}

1 Comment

But you break encapsulation with this InitialSomeThings property setter. This setter should actually not exist.
0

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});

1 Comment

I know :) Maybe the example was a little too simplistic... I was merely trying a way to initialize a property returning an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.