Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable datetime value

Tags:

c#

Can a DateTime value be NULL?

I have this code:

From here I inherit my variable

namespace Transakcija
{
     public class Line
     {
        public System.DateTime DateOfProduction { get; set; }
     }
}

Then for each loop:

foreach (var rw_det in dt_stavke.Rows)
{
    var list = new List<Transakcija.Line>();
    var l = new Transakcija.Line();

     //DateOfProduction
    if (rw_det["DPRO02"].ToString().Length <= 0)
    {
        l.DateOfProduction = default(DateTime);
    }
    else
    {
        l.DateOfProduction = new DateTime();
        prod_date = rw_det["DPRO02"].ToString();
        DateTime pro_date = DateTime.ParseExact(prod_date, "dd.MM.yyyy", CultureInfo.InvariantCulture);
        string p_date = pro_date.ToString("yyyy-MM-dd");
        l.DateOfProduction = DateTime.Parse(p_date);
    }
}

So the value l.DateOfProduction needs to be null. I have tried this:

DateTime? dt = null;
l.DateOfProduction = (DateTime)dt;

But I got error: nullable object must have a value

So is this possible or do I have to pass the minimum datetime value to the variable?

like image 759
CrBruno Avatar asked Apr 19 '26 14:04

CrBruno


1 Answers

DateTime is a value type, so no it can never be null. If you need a "no value" value, use a Nullable<DateTime> or for short DateTime?

like image 129
BrokenGlass Avatar answered Apr 21 '26 02:04

BrokenGlass



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!