none
POCO property default values question RRS feed

  • Question

  • when using the short version for properties in POCO's eg public string CreationDate { get; set; } is it correct when a default value is needed to put these in the class constructor

    eg public Customer() { CreationDate = DateTime.Now; } ?

     

    Or is it better using the 'long' version:

    private
    DateTime creationDate;

    public DateTime CreationDate
    {

    get { return this.creationDate; }
    set
    {

    if (value != null) this.creationDate = value;

    else this.creationDate = DateTime.Now;

    }}

    Thanks.

     


    Wednesday, June 29, 2011 8:13 PM

Answers

  • Hi,

    It should be safe to just assign it in the default constructor.

    Your second code would not work for two reasons:

    1. It would never be valid since value would never be null since your CreateDate is a a DateTime and not nullable DateTime (the datetime type is a value type (struct) not a reference type (class)). (Actually you would get a compiler error if I'm not mistaken)
    2. If your CreationType had been a reference (eg. a nullable DateTime), the default value is only set when anyone assigns CreationDate to null. You need to return (or assign creationDate to) DateTime.Now in the getter if creationDate is null.

     


    --Rune
    Thursday, June 30, 2011 6:10 AM

All replies

  • Hi,

    It should be safe to just assign it in the default constructor.

    Your second code would not work for two reasons:

    1. It would never be valid since value would never be null since your CreateDate is a a DateTime and not nullable DateTime (the datetime type is a value type (struct) not a reference type (class)). (Actually you would get a compiler error if I'm not mistaken)
    2. If your CreationType had been a reference (eg. a nullable DateTime), the default value is only set when anyone assigns CreationDate to null. You need to return (or assign creationDate to) DateTime.Now in the getter if creationDate is null.

     


    --Rune
    Thursday, June 30, 2011 6:10 AM
  • Hi GuyD,

    I am writing to check the status of the issue on your side. Would you mind letting us know the result of the suggestions?

    If you need further assistance, please feel free to let me know. I will be more than happy to be of assistance.

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, July 5, 2011 6:59 AM
    Moderator