When you create a project, if you have a date field, you can enter a date field without entering a value. If you directly convert datetime to null, an error occurs. The following error message is displayed:
Cannot convert null to "system. datetime" because it is a value type
After checking the relevant information on the Internet, find the solution:
Nullable <datetime> now = datetime. now;
Nullable <datetime> now = NULL;
Of course, it can also be abbreviated:
Datetime? Now = datetime. now;
Datetime? Now = NULL;
We can assign values to now directly, but actually assign values to now. value.
Since it can be null, it involves judgment. The following two methods are feasible:
If (now! = NULL ){}
If (now. hasvalue ()){}
One thing to note is that the value type can be changed to the reference type through this method, but the reference type cannot be yo. For exampleCode:
Nullable <string> test = "test ";
If the code compilation fails, the following exception is reported:
Error 1 type "string" must be a value type that cannot be blank to be used as a generic type or parameter "T" in the method "system. nullable <t>"