Default keywords in generic code

Source: Internet
Author: User

Default keywords in generic code]

One problem that occurs in generic classes and generic methods is how to assign the default value to parameterized type T when the following conditions are unknown:

  • T is the reference type or value type.

  • If t is of the value type, whether it is a value or a structure.

Given a variable t of the parameterized type T, the Statement t = NULL is valid only when T is of the reference type; only when T is of the numerical type rather than the structure, statement t = 0 can be used normally. The solution is to use the default keyword,This keyword returns NULL for the reference type and zero for the value type. For the structure, this keyword returns each structure member whose Initialization is zero or null.Depends on whether the structure is a value type or a reference type. The following example from the genericlist <t> class shows how to use the default keyword. For more information, see generic overview.

public class GenericList<T>{    private class Node    {        //...        public Node Next;        public T Data;    }    private Node head;    //...    public T GetNext()    {        T temp = default(T);        Node current = head;        if (current != null)        {            temp = current.Data;            current = current.Next;        }        return temp;    }}
View code

Reference: http://msdn.microsoft.com/zh-cn/library/xwth0h0d (V = vs.90). aspx

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.