1

I'm trying to create a dynamic array which starts with 3 elements. I want to use addColumn to add an element to string[] name. But I guess the the addColumn function is not doing what I expected.What do I need to archieve that functionality? I guess I need saomething like "name.addElement()"?

class LogData
{
    private string[] name;
    private int numberOfColumns;

     public LogData()
     {
         name = new string[3];
         numberOfColumns = name.Length;    
     }

     public void addColumn()
     {
         name = new string[1];// Thats not working, after calling, the number of columns is still 3
     }

     public int getNumberofcolumns()
     {
         return numberOfColumns;
     }
}

I call in the main fucntion:

LogData logData = new LogData();

Console.Write(logData.getNumberofcolumns() + "\n");
logData.addColumn();
Console.Write(logData.getNumberofcolumns() + "\n");

Console.Write("done...\n\n");
Console.ReadLine();

The output is:

3
3
done...
xy36
  • 315
  • 1
  • 11

4 Answers4

2

Are you lloking for

  public void addColumn() {
    Array.Resize(ref name, name.Length + 1);
  }

But, IMHO, a better solution is to change String[] to List<String>:

  class LogData
  {
    private List<String> name = new List<String>();

    ...
    public void addColumn() {
      name.Add(null);
    } 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

Use List<string> instead of the array.

Bewar Salah
  • 567
  • 1
  • 5
  • 15
1

You only assign the number of columns once, it doesn't get the length of the name whenever you call it, the whole field is pointless

 public int getNumberofcolumns()
 {
     return name.Length;
 }

Note: Of course, a list would be preferred.

Sayse
  • 42,633
  • 14
  • 77
  • 146
1

You should use a List<string> which offers you a ton of libraries for manipulating it, and it covers all your requirements. here's the doc

Usage:

List<string> names = new List<string>();

//adding an item
names.Add('YourString');
//getting the length
names.Count();
Louie Almeda
  • 5,366
  • 30
  • 38