74 out of 83 rated this helpful - Rate this topic

default Keyword in Generic Code (C# Programming Guide)

In generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T when you do not know the following in advance:

  • Whether T will be a reference type or a value type.

  • If T is a value type, whether it will be a numeric value or a struct.

Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. The following example from the GenericList<T> class shows how to use the default keyword. For more information, see Generics 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;
    }
}

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Wrong logics in the sample
1. the local variable "current" should be declared as the data member of the list class to keep the status of the list pointer.
2. the initialization of the list pointer "current" should not be in GetNext(). Class constructor would be more appropriate.

Edit by SJ at MSFT: That example was replaced in later versions of the topic, and is now too old for me to update. Here is the current version: http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx. Thanks.
Advertisement