Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable Types as Property

Is it ok to construct my object entities with this type?

   public class Patient
   {
        public Datetime? AdmissionDate { get; set; }
        public double? AdmissionFee { get; set }
        public int? RoomNumber { get; set }
    }

WHat is the drawback if I implemented this in all my entities, because recently, I always encounter situation where I really need to set the value to null, specially in DateTime. My current solution was put DateTime.MinValue when fetching null datetimes record from the database, and when Im displaying the result to Ui, I just check it like this.

    if (patient.AdmissionDate == Datetime.MinValue)
    {
         DisplayAdmissionDate(string.empty)
    }
    else
     {
        DisplayAdmissionDate(patient.AdmissionDate)
    }

Yes, in gridview, I have to put it on the Databound event, so when i have million data to display, I thought checking each of the datetime's each loop was not the most elegant way so, to this problem, I find this ? type where I can put null values, and I'm planning to ?ed all my properties, so in the future, putting null values to this value types will not be a problem. Any advise guys? TIA

like image 326
CSharpNoob Avatar asked Feb 26 '23 04:02

CSharpNoob


1 Answers

This is one of those situations where no single, dogmatic answer covers all cases.

You can’t get away with always using nullable types (or always avoiding them). You should think about each case and use the one that you actually need.

You mentioned that you often needed a nullable DateTime. So why can’t you just use a DateTime? in those cases? This should be an independent consideration from all other fields, especially ints.

The null value in nullable types is intended to mean the value is something like unspecified, unavailable or unknown. There are many situations where this concept exists (e.g. users on a website may or may not specify their date of birth, so that should be a DateTime?), but there are also many situations where this concept makes no sense (e.g. the number of items in a List — if the List itself isn’t null, then clearly it has a definite number of items, so that should be int, not int?).

like image 90
Timwi Avatar answered Mar 11 '23 01:03

Timwi