Skip to content

Array Initialization and actual number of elements in the ar

Sairam Soham

Asked Jun 10, 2015, 9:23 AM EDT1 answer
Share
LinkedInX

Do we need to initialize array?

I have a following piece of code

Code
string[] monthToProcess=new string[12];
            int i = 0;
            foreach (DataColumn column in ds.Tables[0].Columns)
            {

                if (column.ColumnName.Contains(monthColumnString))
                {

                    monthToProcess[i] = column.ColumnName;
                    i = i + 1;

                }
            }
           int j = monthToProcess.Length;

If I don't initialize array
instead of string[] monthToProcess=new string[12];
if I have only string[] monthToProcess;

I get error

But if initialize to its maximum size which is 12 then no matter if I have 2 elements I get monthToProcess.Length

I want it should give me the length as 2 (actual number of elements in the array).

How to do this?

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    Its resolved.
     
    Instead of array I used list
    Code
    List<String> monthToProcess = new List<string>();
    
                foreach (DataColumn column in ds.Tables[0].Columns)
                {
                   if (column.ColumnName.Contains(monthColumnString))
                    {
    
                      monthToProcess.Add( column.ColumnName);
    
                    }
                }
    int j = monthToProcess.Count;
    0