Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
Visual Studio
Visual C#
Generics
 default Keyword
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
C# Programming Guide
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.

C#
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;
    }
}
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Wrong logics in the sample      sendtovinnie ... SJ at MSFT   |   Edit   |   Show History
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.
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2012 Microsoft. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker