157 recommendations for writing high-quality code to improve C # programs--Recommendation 35: Use default to specify initial values for generic type variables

Source: Internet
Author: User

Recommendation 35: Use default to specify an initial value for a generic type variable

Some algorithms, such as the Find algorithm for generic collection list<t>, may be looking for a value type, or possibly a reference type. Within this algorithm, we often specify default values for these value types or reference type variables. So the problem is that the default initial value of a value type variable is a value of 0, whereas the default initial value of a reference type variable is a null value, which obviously causes the following compilation error:

         Public T func<t>()        {            null; return t;        }

Cannot convert null to type parameter ' T ' because it may be a non-nullable value type. Consider using "Default (T)" instead.

         Public T func<t>()        {            0;             return t;        }

The type "int" cannot be implicitly converted to "T".

So the above code should read:

         Public T func<t>()        {            default(t);             return t;        }

Thus, if it encounters t as an integer at run time, the runtime assigns it a value of 0, and if T is a reference type such as a person at run time, it will be assigned a null value.

List<t> 's Find method source code is:

[__dynamicallyinvokable] PublicT Find (predicate<t>match) {    if(Match = =NULL) {throwhelper.throwargumentnullexception (exceptionargument.match); }     for(inti =0; I < This. _size; i++)    {        if(Match ( This. _items[i])) {            return  This. _items[i]; }    }    return default(T);}

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--Recommendation 35: Use default to specify initial values for generic type variables

Related Article

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.