0

I have a class as follows, its for an API so it must be in this format

public class Command
{
    public string response_type { get; set; }
    public string text { get; set; }
    public Attachment[] attachments { get; set; } = new Attachment[] { new Attachment { } };
}

public class Attachment
{
    public string title { get; set; }
    public string title_link { get; set; }
    public string image_url { get; set; }
}

So its a response_type, text and array of attachments. You can see I create the attachment array and create an empty object.

When creating the object there will only ever be one element in the array.

How do I set or add to the array when declaring the object, given the object is already created in the constructor

Command result = new Command()
{
    text = "Rebooting!",
    attachments[0] = ????
};

Im missing something simple, tried lots of combos

2
  • You want to add elemenets to an array during runtime? Commented Jan 16, 2016 at 15:54
  • You can create a constructor(s) with parameters. One of the parameters can be an array. Your constructor doesn't have any parameters in the parameter list. Commented Jan 16, 2016 at 16:33

2 Answers 2

3

To add to the array you need to do it after the construction

Command result = new Command()
{
    text = "Rebooting!",
};

result.attachments = new Attachment[2] { result.attachments[0], new Attachment() };

If you just want to set the value (since array is already created and contains one instance you can do

result.attachments[0] = new Attachment();
Sign up to request clarification or add additional context in comments.

1 Comment

Oops, actually noticed it was an array. Array does not have an Add method, you would need to use a List<Attachment> instead. Edited the answer to add 1 additonal instance to the created array.
3

You can use the array initializer and just ad one item:

Command result = new Command()
{
    text = "Rebooting!",
    attachments = new [] {new Attachment {...} }
};

As a side note, most .NET naming standards start property names with a capital letter (Attachments)

4 Comments

You didn't assume this was asked before?
Thanks however I already have the array initialised in the constructor, thus it already has one array element.
@DaleFraser You can't easily "add" to an array at runtime - you have to reallocate space for a new larger array. Either overwrite the array with a new one or use a private List<T> and expose it as array via a property getter.
Thanks but Im not adding to the array, the array exists, I just want to set it, the other answer is what I was looking for thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.