C#
  Home arrow C# arrow Page 4 - Generics, Dictionaries, and More
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Generics, Dictionaries, and More
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 3
    2008-12-24

    Table of Contents:
  • Generics, Dictionaries, and More
  • 4.10 Using foreach with Generic Dictionary Types
  • 4.11 Constraining Type Arguments
  • 4.12 Initializing Generic Variables to Their Default Values

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Generics, Dictionaries, and More - 4.12 Initializing Generic Variables to Their Default Values


    (Page 4 of 4 )

    Problem

    You have a generic class that contains a variable of the same type as the type parameter defined by the class itself. Upon construction of your generic object, you want that variable to be initialized to its default value.

    Solution

    Simply use the default keyword to initialize that variable to its default value:

      public class DefaultValueExample<T>
      {
        
    T data = default(T);

         public bool IsDefaultData()
         {
           
    T temp = default(T);

            if (temp.Equals(data))
            {
              
    return (true);
            }
            else
            {
              
    return (false);
            }
         }

         public void SetData(T val)
         {
            data = val;
         }
      }

    The code to use this class is shown here:

      public static void ShowSettingFieldsToDefaults()
      {
         DefaultValueExample<int> dv = new DefaultValueExample<int>();

         // Check if the data is set to its default value; true is returned.
         bool isDefault = dv.IsDefaultData();
         Console.WriteLine("Initial data: " + isDefault);

         // Set data.
        
    dv.SetData(100);
        
    // Check again, this time a false is returned.
        
    isDefault = dv.IsDefaultData();
        
    Console.WriteLine("Set data: " + isDefault);
      }

    The first call toIsDefaultDatareturnstrue, while the second returnsfalse. The output is shown here:

      Initial data: True
      Set data: False

    Discussion

    When initializing a variable of the same type parameter as the generic class, you cannot just set that variable to null. What if the type parameter is a value type such as an int or char? This will not work because value types cannot be null. You may be thinking that anullabletype such aslong?orNullable<long>can be set tonull(see Recipe 4.6 for more on nullable types). However, the compiler has no way of knowing what type argument the user will use to construct the type.

    Thedefaultkeyword allows you to tell the compiler that at compile time the default value of this variable should be used. If the type argument supplied is a numeric value (e.g.,int,long,decimal), then the default value is zero. If the type argument supplied is a reference type, then the default value isnull. If the type argument supplied is astruct, then the default value of thestruct is determined by initializing each member field to its default value.

    See Also

    Recipe 4.6, and the “default Keyword in Generic Code” topic in the MSDN documentation.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · This article is an excerpt from the book "C# 3.0 Cookbook, Third Edition," published...
     

    Buy this book now. This article is excerpted from chapter four of the C# 3.0 Cookbook, Third Edition, written by Jay Hilyard and Stephen Teilhet (O'Reilly, 2008; ISBN: 059651610X). Check it out today at your favorite bookstore. Buy this book now.

    C# ARTICLES

    - Cyclic Redundancy Check
    - Handling Methods and Functions
    - Destroying Objects in C#
    - Creating Objects in C-Sharp
    - Classes and Objects
    - Programming Languages: Managed versus Native
    - LINQ-to-MySQL with DbLinq in C#
    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    Stay green...Green IT