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

Dale Fraser
  • 4,623
  • 7
  • 39
  • 76
  • You want to add elemenets to an array during runtime? – AustinWBryan Jan 16 '16 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. – jdweng Jan 16 '16 at 16:33

2 Answers2

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)

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • You didn't assume this was asked before? – Amit Jan 16 '16 at 15:57
  • Thanks however I already have the array initialised in the constructor, thus it already has one array element. – Dale Fraser Jan 16 '16 at 15:59
  • 2
    @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` and expose it as array via a property getter. – D Stanley Jan 16 '16 at 16:09
  • 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. – Dale Fraser Jan 16 '16 at 16:11
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();
Janne Matikainen
  • 5,061
  • 15
  • 21
  • Oops, actually noticed it was an array. Array does not have an Add method, you would need to use a List instead. Edited the answer to add 1 additonal instance to the created array. – Janne Matikainen Jan 16 '16 at 16:14