William
William

Reputation: 3395

Reconciling properties of structs and DateTime

I have been looking through the DateTime structure and I am slightly confused.

My understanding with structs is that you cannot assign 'default values' of fields. If the default constructor of a struct is used (which is not something that you can control), then any fields will be initialized using the default values of their value type.

This is all good and well, but why then is the default value of the 'Days' property of a DateTime equal to 1? How do they pull that off?

William

Upvotes: 2

Views: 143

Answers (2)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

Jon Skeet is right it's all about the difference between fields and other members. One could really make a "date time" like this:

struct MyDateTime
{
  // This is the only instance field of my struct
  // Ticks gives the number of small time units since January 1, 0001, so if Ticks is 0UL, the date will be just that
  readonly ulong Ticks;

  // here goes a lot of instance constructors,
  // get-only instance properties to show (components of) the DateTime in a nice way,
  // static helper methods,
  // and lots of other stuff, but no more instance fields
  ...
}

So in reality, MyDateTime is just a wrapped ulong with an interpretation, and a lot of nice ways to show and manipulate that ulong.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500625

You need to understand the difference between fields and properties.

The fields are all initialized to 0, but the properties can do what they like with those fields. Sample:

public struct Foo
{
    private readonly int value;

    public Foo(int value)
    {
        this.value = value;
    }

    public int ValuePlusOne { get { return value + 1; } }
}

...

Foo foo = new Foo(); // Look ma, no value! (Defaults to 0)
int x = foo.ValuePlusOne; // x is now 1

Now obviously DateTime is a smidge more complicated than this, but it gives the right idea :) Imagine what "A DateTime with the field explicitly set to 0" would mean... the "default" DateTime just means exactly the same thing.

Upvotes: 7

Related Questions