C # Set the datetime type variable value to null

Source: Internet
Author: User

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>"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.