I would like to create a property backed by a DateTime struct, however, because structs are value types, MyClass.MyDate.AddDays(1) doesn’t work as expected for the following class:
public class MyClass
{
public DateTime MyDate { get; set; }
}
The desired behavior would be to have the DateTime property increase by one day, but in my example, the property keeps it’s initial value. I can get the same result with the code MyClass.MyDate = MyClass.DateTime.AddDays(1), but this is counterintuitive. I understand why this doesn’t work, but I’m not sure of the best way to work around it.
What is the accepted way to create the MyDate property so that the exposed DateTime methods like AddDays() update the instance variable?
MyClass.MyDate = MyClass.DateTime.AddDays(1)This is the standard behavior of a struct. All standards-compliant structs are immutable, except those with a VERY good reason.
If you really have a problem with the above syntax, I recommend something like this: