No clue about arrays, everything fails ...

I want to fill an array in the constructor of my object, and then use it in
in another method. But no matter what I try, I can't get this right. It is too different from how arrays used to be. Either it does not compile, or the array remains null as in the example below. How should I do it

class
Calendar

{
private static int day,month;
private static int[] daysPerMonth;

public Calendar()
{
day=16;
daysPerMonth[1] = 31;
daysPerMonth[2] = 28;
daysPerMonth[3] = 31; // does not work, daysPerMonth remains null
// ...
}

public static AddDay()
{
day++;
if (day>daysPerMonth[month])
{month++; day=1;}
// ...
}

Regards,

  Guido



Answer this question

No clue about arrays, everything fails ...

  • Big_Show

    Yes, that is what I was looking for, I think.
    I didn't find it at first because it isn't called ArrayList but simply List.

    Regards,

      Guido

  • Pierre123

    Thanks. Smile

    I will be changing the number of months, days etc. since it is a different world, so I can't use any Earth-based calendars.

    This also means that specifying the length of the array in the declaration is something I would rather not do, since we could have a year with many more months than 12. The specifics will eventually be read from a file.

    Regards,

      Guido


  • brave43

    ArrayList is in the System.Collections namespace.  "using" this namespace will allow you access to the ArrayList class.

  • vitamin

    If your arrays need to be that dynamic you might want to look at the ArrayList.

  • Raks

    re: m_str = new string [size]

    doesn't this come up with a compilation error "A constant value is expected"


  • Farooq Azam

    You need to initialize the array, just like any other class:

    private static int[] daysPerMonth = new int[12];


    Note that the array index will start at 0.

    PS: There're ready to use Calendar classes in the framework (in the System.Globalization namespace), and the DateTime class has a static method to calculate the number of days in any given month (it also requires a year argument to take leap years into account).


  • Haritvm

    Not in C#. It would in C++.

  • .NET Developer

    "The specifics will eventually be read from a file."

    You can initalize the array size with a variable.  IE:


     class Tmp
     class Tmp
     {
      public string[] m_str;
      public Tmp(string thesize)
      {
       int size = Int32.Parse(thesize);
       m_str = new string[size];
       for(int i = 0; i < size; i++)
       {
        m_str[ i ] = i.ToString();
       }
      }

     }
     




  • Watson How

    thanks Matthew, I'd just had a mental block about how to define the array size this afternoon...bizarre.
  • No clue about arrays, everything fails ...