简体   繁体   中英

what happens if default value is null and convert to string

to be more specific, I have DateTime? BirthDate

my question is what will happen in this case:

lblBirthDate.Text = myObject.BirthDate.GetValueOrDefault().ToString();

if BirthDate will be null. I have resharper installed, and it doesn't warn me that I could have a null problem there...

If BirthDate is null , you get the localized string representation of the default instance of DateTime . That is, you'll get the string representation of 00:00:00.0000000, January 1, 0001.

You don't get a warning from ReSharper because you don't have a null problem there. It is not a runtime exception to call Nullable<T>.GetValueOrDefault on a null instance of a Nullable<T> . Instead, you get the default value if you have a null instance. That's exactly what GetValueOrDefault means: get Value if HasValue is true , otherwise get the default value for the underlying struct type.

I'm pretty sure GetValueOrDefault returns DateTime.MinValue in the case of null.

Here's a few ways you can handle null values:

DateTime? myNullDate = null;

DateTime myDate;
myDate = myNullDate ?? DateTime.Now; // myDate => DateTime.Now
myDate = myNullDate ?? default(DateTime); // myDate => DateTime.MinValue
myDate = myNullDate.GetValueOrDefault(DateTime.Now); // myDate => DateTime.Now
myDate = myNullDate.GetValueOrDefault(); // myDate => DateTime.MinValue

Resharper won't show you any error because the default value for DateTime is 1/1/1 00:00:00. You can get the default value for any type using the default operator:

DateTime defaultDateTime = default(DateTime);

This value is exactly the same as DateTime.MinValue

If you need to use nulls, you must declare your property as nullable:

DateTime? BirthDay { get; set; };

The nullable DateTime DateTime? supports calling ToString() without error even if the value is null, giving an empty string if so. Then you don't have to worry about nulls.

Is much more consistent using a nullable DateTime than having a special value to represent missing values, like default(DateTime) , ie DateTime.MinValue;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM