What kind of data do you use to store the date of death in a register (Datetime or string)?

Asked

Viewed 91 times

5

I have a record of people where I need to store birth dates (DateBirth) and death (DateDeath). Knowing that the guy DateTime in C# cannot be empty and its default initial value is 01/01/0001 00:00:00, which makes no sense to fill in a field that deals with a person’s death date, which solution you would apply?

They would still define the property as the type DateTime and would do some kind of treatment afterwards? They would define it as string? Or what other solution they might suggest?

Below, excerpt from entity class code in C#.

public class Person
{
    public string Name { get; set; }
    public string Gender { get; set; }
    public DateTime DateBirth { get; set; }

    // Definir a propriedade como DateTime há um valor inicial pré-definido: 01/01/0001
    // public DateTime DateDeath { get; set; }
    
    // Ou definir a propriedade como string, iniciando-a com valor vazio,
    // mas sem os recursos de validação do tipo DateTime.
    // public string DateDeath { get; set; }
}   

1 answer

6


Use DateTime? (cancellable type) which permits a null value and so may indicate that that date does not yet exist. Obviously you need to treat properly to not generate errors, but since C# 8 this has become easier, I recommend using at least this version and adopt its practices. Do not use string, That doesn’t make any sense.

In fact, if you are programming correctly and in a modern way all types are not voidable and only using the interrogation do they become voidable. See more in Is there a disadvantage or is it harmful to use null types?.

  • Thanks for the help Maniero. I will follow your tip!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.