0

I have the following code. Would anyone tell me if this is correct according to C# rules.

public DateTime[] datetime = new DateTime[];

I am unable to use get; set with the above.

And subsequently, I want to save dates to datetime.

How to do it?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Unnikrishnan
  • 523
  • 1
  • 8
  • 18
  • 1
    In C# 6.0 (Visual Studio 2015, or 2013 with Roslyn), the following statement will be supported: `public DateTime[] datetime { get; set; } = new DateTime[4];` –  May 10 '15 at 04:58

2 Answers2

3

Would anyone tell me if this is correct according to C# rules.

I'm not sure what you mean by rules. But, according to the C# specification, you have to specify the size of the array when declaring it:

public DateTime[] datetime = new DateTime[5];   

I am unable to use get; set with the above.

Because that isn't the correct syntax for declaring a property. You do it like this:

public DateTime[] DateTimes { get; set; }

And you initialize it via a constructor:

class Foo
{
    public Foo()
    {
        DateTimes = new DateTime[5];
    }

    public DateTime[] DateTimes { get; set; }
}

Which will now give you an array with 5 elements

Note that if you know the amount of dates beforehand, you can use array initializer syntax as well:

class Foo
{
    public Foo()
    {
        DateTimes = { new DateTime(1, 1, 1970), new DateTime(2, 1, 1980) };
    }

    public DateTime[] DateTimes { get; set; }
}

If the array size isn't known beforehand, you should perhaps consider using a List<DateTime> which can be expanded at runtime.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
1

You cannot declare and initialise a property at the same time, unlike with a field. Instead initialise it in your class' constructor:

public DateTime[] datetime { get; set; }

public MyClass()
{
  datetime = new DateTime[];
}

If your array is not a fixed size and you'll be adding an unknown amount of dates to it, consider using a List instead:

public List<DateTime> datetime { get; set; }

public MyClass()
{
  datetime = new List<DateTime>();

  // Add a DateTime:
  var newDateTime = DateTime.Now;
  datetime.Add(newDateTime);
}
UncleDave
  • 6,872
  • 1
  • 26
  • 44