Home > Software engineering >  C# 9.0 Record constructor with non-nullable property but with default values
C# 9.0 Record constructor with non-nullable property but with default values

Time:10-05

I am trying to define a record type for the following, instead of being a class

public class Contact
{
    public string Name {get;set;}
    public string Email {get;set;}
    public string PhoneNo  {get;set;}
    public DateTime UpdatedAt {get;set;} = DateTime.Now;
}

Since UpdatedAt is a non-nullable field, if I am using the most basic constructor of a record, we will need to pass DateTime.Now everytime we call the record. Is there any other way to do it? Instead of doing this:

public record Contact(string Name, string Email,string PhoneNo, DateTime UpdatedAt);

var records = new Contact("My Name", "[email protected]", "123456", DateTime.Now)

CodePudding user response:

You can give a record type a constructor, so add one that takes all 4 properties, but make the DateTime nullable and default to null. If it's null then have the constructor use DateTime.Now. For example:

public record Contact
{
    public Contact(string name, string email, string phoneNo, DateTime? updatedAt = null)
    {
        this.Name = name;
        this.Email = email;
        this.PhoneNo = phoneNo;
        this.UpdatedAt = (updatedAt ?? DateTime.Now);
    }

    public string Name {get;set;}
    public string Email {get;set;}
    public string PhoneNo  {get;set;}
    public DateTime UpdatedAt {get;set;};
}
  • Related