0

I'm reading back a number of properties into the constructor of an object. One of the properties is a calculated off another property.

But when I create this object the calculated Implementation_End_String property value is always null:

    private string implementationEndString;
    public string Implementation_End_String {
        get{
            return implementationEndString;
        }
        set  {

            implementationEndString= DataTimeExtensions.NullableDateTimeToString(Implementation_End);
        }
    }

Question:

How can you pass in a calculated property to an object constructor?

This is a gist of the ctor and calculated property:

    private string implementationEndString;
    public string Implementation_End_String {
        get{
            return implementationEndString;
        }
        set  {

            implementationEndString= DataTimeExtensions.NullableDateTimeToString(Implementation_End);
        }
    }



    public DateTime? Implementation_End { get; set; }


    public ReleaseStatus(DateTime? implementationEnd)
    {

        //value is assigned at runtime
        Implementation_End = changeRequestPlannedImplementationEnd;



    }
Brian J
  • 5,416
  • 19
  • 94
  • 189
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – mybirthname Oct 14 '16 at 10:57

2 Answers2

1

Write it this way.

private string implementationEndString = DataTimeExtensions.NullableDateTimeToString(Implementation_End);

public string Implementation_End_String 
{
    get{ return implementationEndString; }
    set{ implementationEndString=value; }
    //if you don't want this property to be not changed, just remove the setter.
}

After that when you get the property value it will take the value of DataTimeExtensions.NullableDateTimeToString(Implementation_End);. In your code, when you try to get the implement returns null, because implementationEndString is null.

mybirthname
  • 16,991
  • 3
  • 29
  • 48
  • That gave a compiler error `A field initializer cannot reference the nonstatic field, method, or property`. Clearly because NullableDateTimeToString is a static method. Not sure what to do in this case. – Brian J Oct 14 '16 at 16:26
1

No need for the field implementationEndString. Just make Implementation_End_String a read-only property and create the string from the other property when needed:

public string Implementation_End_String
{
    get
    {
        return DataTimeExtensions.NullableDateTimeToString(Implementation_End);
    }
}
Henrik
  • 22,652
  • 6
  • 38
  • 90