Search code examples
c#asp.netasp.net-mvcentity-frameworkviewmodel

Using setter in ViewModel using another property


I have the following ViewModel in my app and there is two BirthDate property (with / without time). When using set { } without body I encounter "Not using the value means that the accessor ignores the caller's intent which could cause unexpected results at runtime.". Then I added a private property and update set as set { birthDateWithTime = value; }. However, this time birthDateWithTime private property not sees to be used. Is there any mistake regarding to implementation below? I want to use both property separately and do not want to convert in JavaScript or code.

    public class DemoViewModel
    {
        public int Id { get; set; }

        public DateTime BirthDate { get; set; }

        private string birthDateWithTime;

        public string BirthDateWithTime {
            get { return BirthDate.ToString("dd/MM/yyyy - HH:mm"); }
            set { birthDateWithTime = value; }
        }
    }

Solution

  • @Gabriel Llorico answer is correct. or maybe you can try another one.

    private DateTime _birthDate;
    public DateTime BirthDate{
       get{
          return _birthDate;
       }
       set{
         this._birthDate = value;
         this.BirthDateWithTime = this._birthDate.ToString("dd/MM/yyyy - HH:mm");
       }
    }
    public string BirthDateWithTime{get;set;}