1

I'm writing a serializable object that contains a collection. So, in order to be able to add and remove items from that collection, I added methods that would first convert the collection from an Array into a List, add or remove the items and then convert the List back into a Array.

public void AddElement(Element element) {
   List<Element> list = new List<Element>(this.elements);
   list.Add(element);
   this.elements = list.ToArray();
}

Is there maybe a problem creating the List like this?

List(this.elements)

Or is it a problem, that the Array is Length is 0 at start?

EDIT1: converting from a list field also leaves an empty array.

EDIT2: XML Serialization is not wanted.

globalenemy
  • 109
  • 2
  • 11

1 Answers1

2

Your code works fine. Here is the MCVE:

Program.cs

using System;

namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {
            var test = new TestClass();
            test.AddElement(new Element());
            Console.WriteLine(test.HowMuch());
        }
    }
}

TestClass.cs

using System.Collections.Generic;

namespace Test1
{
    class TestClass
    {
        private Element[] elements = new Element[0];

        public void AddElement(Element element)
        {
            List<Element> list = new List<Element>(this.elements);
            list.Add(element);
            this.elements = list.ToArray();
        }

        public int HowMuch()
        {
            return elements.Length;
        }
    }
}

Element.cs

namespace Test1
{
    class Element
    {
    }
}

The example outputs 1, not 0.

The most probable reason is that you assign this.elements to a variable, hence, store old version of the array.

enkryptor
  • 1,574
  • 1
  • 17
  • 27