-1

So i have this object output

object output = new[] { "string1", "string2", "string3" };

but later down the line i want to append "string4" to it. So i tried:

output.Add("string4");

but I'm getting a 'object' does not contain a definition for 'Add' so i tried the following:

((Array) output).Add("string4"); // also does not contain a definition for 'Add'
((List<string>) output).Add("string4"); // which gets rid of the red lines, but will this work with the initial contents of output?

I am not able to change the initialization. So I'm wondering if there is a cleaner way to do this. Thanks!

  • 2
    arrays are fixed size, use a list instead - as per Nigel answer – pm100 Jun 02 '22 at 00:08
  • `object output = new[] { "string1", "string2", "string3" };` **does not** mean "`output` is an array of these objects". It means "`output` is an object, which specfically is this array". Because the fact that it's an array isn't declared in the variable type, array methods are not available - the *static* type does not provide them. That said, C# arrays don't have an `.Add` method, and can't be resized. You were presumably thinking of some other sequence type, such as `List`. – Karl Knechtel Jun 02 '22 at 00:10

1 Answers1

0

Try this instead:

List<string> output = new List<string> { "string1", "string2", "string3" };
output.Add("string4");
Nigel
  • 2,961
  • 1
  • 14
  • 32
  • Yes, i could, but i did indicate that I am not able to change the initialization. However, I guess i can convert this list with `ToArray()` afterwards. – AJ Godinez Jun 02 '22 at 00:21
  • @AJGodinez that does not have the quite same effect as appending to the array. If you really want to append to an array that is not possible – Nigel Jun 02 '22 at 00:24