开发者

DateTime/bool and Null values in .Net

Utilizing .Net I a开发者_如何学Cm inheriting from an older class that has DateTime and bool parameters as part of its constructor. These values are pulled from a SQL database and in the SQL database these values can be null. When I populate my class and call the base constructor this fails because DateTime and bool cannot have null values in .Net.

I am aware of Nullable types (DateTime? etc.) and I can define my custom classes to utilize them and hold the null values but I have not been able to come up with a way to transfer the null value into a value that the older class with the DateTime could accept.

I hate this idea but, I thought of using a a property to translate the null to a dummy date and then back again but there is no way to determine who is calling the property so I wouldn't know when to feed a null or a dummy date back from the get.

Any Ideas would be greatly appreciated.


We usually use DateTime.MinValue for this sort of thing if you can't use DateTime? in the older code.


You can use the null coalescing operator to use "the current value or a default if missing." As mentioned in another answer, the default date would be a sentinal such as DateTime.MinValue.

private static readonly DateTime DefaultDate = ...;

...

DateTime? optionalDate = ...;
DateTime date = optionalDate ?? DefaultDate;


The older class with a datetime can accept any datetime, so any value would work... (but I would recommend using DateTime.MinValue as others have suggested).

What you might be more (properly) concerned with is how client code that uses instances of the older class will behave when an instance has this "magic" value that represents a null in it.

Is the older clas sealed? If not, Can you create a new derived class with an additional bool DateTimeIsDefined property, and the appropriate code to behave in the appropriate way when the flag is not set (indicating that the DateTime is undefined? if the older clas has it's methods declared as virtual, you could override them in the dervied class with this newer implementation that takes the DateTimeIsDefined property into consideration... and clients that were passed instances of the older class would still execute the older implementation, whereas clients pass instances of the newer class would execute the newer one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜