简体   繁体   中英

DateTime Array with get set in c#

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?

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM