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?
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?
You can assigne a nullable DateTime
by using the constructor :
DateTime? dt = new Nullable<DateTime>();
You can check if a nullable type is null
by using the HasValue
property:
if(dt.HasValue)
{
// now you can safely use dt.Value as DateTime,
// otherwise accessing the Value property raises an InvalidOperationException
DateTime otherDate = dt.Value;
}
yoe can have Dateime Nullable this way
DateTime? dtNullable = new Nullable<DateTime>();
if(dtNullable.HasValue)
l.DateOfProduction = dtNullable.Value;
PS: example if you passing a non nullable DateTime to a Nullable DateTime then it will require casting
Like this
DateTime? nullableDateTime = (DateTime?)nonNullableDateTime;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.