Home > Software design >  ToString() method not working in Modle's Getter/Setter
ToString() method not working in Modle's Getter/Setter

Time:07-19

I have a C# Model that contains a birthday. The birthday field takes the birthday from a separate API in the DateTime format. I've been trying to change this to a String instead, and I want to do it with Getters/Setters, if possible.

I get an error for ToString() when trying to do this. Error states "cannot convert from "string" to "System.IFormatProvider". I've tried lots of other variants of this and I just can not get something to work. I want to be able to achieve it via the Getters/Setters.

public class PersonLookUpModel 
   { 
        public DateTime? DateOfBirth { get; set; }
        public string? _dateOfBirthString;
        public string? DateOfBirthString { 
                         get => DateOfBirth; 
                          set => _dateOfBirthString = value.ToString("MMMM dd"); }
    }

CodePudding user response:

Here you go.

public class PersonLookupModel
{
   public DateTime DateOfBirth{get;set;}
   public string DOBString => DateOfBirth.ToString("MMM dd");
}

CodePudding user response:

This is what ended up working:

public DateTime? DateOfBirth { get; set; }
public string _dobString;
public string DOBString { 
              get => _dobString = DateOfBirth?.ToString("MMMM dd"); 
              set => _dobString = value; }
  • Related