2

Assume I have a custom data object names MyDataObject, defined as such:

    public class MyDataObject
{
    public string Caption { get; set; }
    public int inx { get; set; }
    public string[] inputArr = new string[6];
}

I now can add MyDataObject to a list of objects. As shown below:

public void PopuList()
    {

        var items = new ObservableCollection<MyDataObject>();
        items.Add(new MyDataObject() { Caption = "foo", Checked = false, inx = 0 });
        listBox.ItemsSource = items;
    }

The problem I am having is that I cannot seem to add an array (inputArr as seen in the code above) to MyDataObject. inputArr is to have a length of 6, of which will be customized for each item. Some elements will be left blank. My attempt at getting arrays to add to the MyDataObject is as follows:

items.Add(new MyDataObject() { Caption = "foo", Checked = false, inx = 0, inputArr[0] = "bar" });

For some reason this gives me an error across the entire inputArr[0] = "bar". The error states The name inputArr does not exist in the current context.

I have also tried

items.Add(new MyDataObject() { Caption = "foo", Checked = false, inx = 0, inputArr = { "a","b","c","d","e","f" } });

This however gives me an error on each of the six strings. The error is: string[] does not contain a definition for 'add'

Any clues on adding arrays to custom data objects?

2
  • 1
    new MyDataObject() { Caption = "foo", Checked = false, inx = 0, inputArr = new string[] { "a","b","c","d","e","f" } }; but if you make inputArr a List<string>, your code will work. it will be simpler to transform list inputArrinto a property too Commented Jan 19, 2016 at 18:16
  • 1
    Arrays are so DotNet Framework 1.1'ish. I'd suggest using IList<string> or ICollection<string> Commented Jan 19, 2016 at 18:17

1 Answer 1

1

You can use an array initializer:

items.Add(new MyDataObject() 
{ 
    Caption = "foo", 
    Checked = false, 
    inx = 0, 
    inputArr = new [] { "a","b","c","d","e","f" } 
});

Note

In the definition of MyDataObject, I don't see a property whose name is Checked. If this isn't a property of MyDataObject, you have to remove it from the above object initializer.

Sign up to request clarification or add additional context in comments.

Comments

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.