Set default values for. NET datetime type Variables as parameters

Source: Internet
Author: User

A little tips.

The default value of a function parameter in. NET needs to be a compile-time constant. If the argument is a reference type, you can set NULL, and if it is a value type, you can set the corresponding compile-time constant, such as Integer, but for datetime (struct, value type) How do you want to set the default type?

Typically, the datetime struct is given the default time, that is, DateTime.Now, but DateTime.Now is not compiled at a constant rate and therefore cannot be compiled.

The following code cannot be compiled:

 Public Const DateTime defaultdatetime = DateTime.Now;

However, you can do this by setting the DateTime type parameter to be a nullable type, giving its default parameter null, and making a judgment assignment in the function, as follows:

Static void NULL ) {    datetime.now;}

The idea is to convert the DateTime parameter to a nullable type, give the default value null, and then in the body of the function, first determine whether the parameter is empty, if it is empty, use DateTime.Now to assign a value, otherwise the parameter value is used.

The above content is very simple, just think this Tips is very fun.

Set default values for. NET datetime type Variables as parameters

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.