Minggu, 01 Desember 2024

default Keyword in Generic Code (C# Programming Guide)

 

default Keyword in Generic Code (C# Programming Guide)

Visual Studio 2010

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. For nullable value types, default returns a System.Nullable(Of T), which is initialized like any struct.

The following example from the GenericList<T> class shows how to use the default keyword. For more information, see Generics Overview.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Test with a non-empty list of integers.
            GenericList<int> gll = new GenericList<int>();
            gll.AddNode(5);
            gll.AddNode(4);
            gll.AddNode(3);
            int intVal = gll.GetLast();
            // The following line displays 5.
            System.Console.WriteLine(intVal);

            // Test with an empty list of integers.
            GenericList<int> gll2 = new GenericList<int>();
            intVal = gll2.GetLast();
            // The following line displays 0.
            System.Console.WriteLine(intVal);

            // Test with a non-empty list of strings.
            GenericList<string> gll3 = new GenericList<string>();
            gll3.AddNode("five");
            gll3.AddNode("four");
            string sVal = gll3.GetLast();
            // The following line displays five.
            System.Console.WriteLine(sVal);

            // Test with an empty list of strings.
            GenericList<string> gll4 = new GenericList<string>();
            sVal = gll4.GetLast();
            // The following line displays a blank line.
            System.Console.WriteLine(sVal);
        }
    }

    // T is the type of data stored in a particular instance of GenericList.
    public class GenericList<T>
    {
        private class Node
        {
            // Each node has a reference to the next node in the list.
            public Node Next;
            // Each node holds a value of type T.
            public T Data;
        }

        // The list is initially empty.
        private Node head = null;

        // Add a node at the beginning of the list with t as its data value.
        public void AddNode(T t)
        {
            Node newNode = new Node();
            newNode.Next = head;
            newNode.Data = t;
            head = newNode;
        }

        // The following method returns the data value stored in the last node in
        // the list. If the list is empty, the default value for type T is
        // returned.
        public T GetLast()
        {
            // The value of temp is returned as the value of the method. 
            // The following declaration initializes temp to the appropriate 
            // default value for type T. The default value is returned if the 
            // list is empty.
            T temp = default(T);

            Node current = head;
            while (current != null)
            {
                temp = current.Data;
                current = current.Next;
            }
            return temp;
        }
    }
}


Community Content Add
Annotations FAQ
default.aspx /StateManagement
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<%@ Register src="~/wuc/ViewProduct.ascx" tagname="ViewProduct" tagprefix="wuc" %>

<%@ Register src="wuc/ViewCart.ascx" tagname="ViewCart" tagprefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <!--<link href="App_Themes/ThemeSilver/silver.css" rel="stylesheet" type="text/css" />-->
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <h2>Sportstore</h2>
    Service first.
    <div>
    <!-- Hier een dropdownlist om een theme te selecteren -->

        <asp:DropDownList ID="ddlTheme" runat="server" AutoPostBack="true">
            <asp:ListItem Value="ThemeSilver">Silver Theme</asp:ListItem>
            <asp:ListItem Value="ThemeDark">Dark Theme</asp:ListItem>
        </asp:DropDownList>

    </div>

    <div > 
            <div id="menu">
                <!-- Hier een menu om de productcategorie te selecteren --> 
                <asp:TreeView ID="TreeView1" runat="server">
                </asp:TreeView>
            </div>
            <div id="content">
                <!-- Hier een usercontrol die de producten toont -->
                <asp:Panel ID="pnlProducts" runat="server">
                    <wuc:ViewProduct ID="viewProduct" runat="server" />
                </asp:Panel>
            </div>
      
            <div id="cart">
                 <!-- Hier een usercontrol met de aankoopkar -->
                 <uc1:ViewCart ID="ViewCart1" runat="server" />
                
                
            </div>
     </div>
    </form>
</body>
</html>

Tidak ada komentar: