C#
  Home arrow C# arrow Page 4 - More About Generics
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#

More About Generics
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2008-12-18

    Table of Contents:
  • More About Generics
  • 4.6 Creating a Value Type That Can Be Initialized to Null
  • 4.7 Reversing the Contents of a Sorted List
  • 4.8 Making Read-Only Collections the Generic Way

  • 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


    More About Generics - 4.8 Making Read-Only Collections the Generic Way


    (Page 4 of 4 )

    Problem

    You have a collection of information that you want to expose from your class, but you don’t want any users modifying the collection.

    Solution

    Use the ReadOnlyCollection<T>wrapper to easily support collection classes that cannot be modified. For example, a Lottery class that contained the winning lottery numbers should make the winning numbers accessible but not allow them to be changed:

      public class Lottery
      {
        
    // make a list
        
    List<int> _numbers = null;

         public Lottery()
         {
           
    // pick the winning numbers
           
    _numbers = new List<int>(5) { 17, 21, 32, 44, 58 };
         }

         public ReadOnlyCollection<int> Results
        
    {
           
    // return a wrapped copy of the results
           
    get { return new ReadOnlyCollection<int>(_numbers); }
        
    }
      }

    Lotteryhas aList<int>of winning numbers that it fills in the constructor. The interesting part is that it also exposes a property calledResults, which returns aReadOnlyCollectiontyped as<int>for seeing the winning numbers. Internally, a newReadOnlyCollection wrapper is created to hold theList<int>that has the numbers in it, and then this instance is returned for use by the user.

    If users then attempt to set a value on the collection, they get a compile error:

      Lottery tryYourLuck = new Lottery();
      // Print out the results.
      for (int i = 0; i < tryYourLuck.Results.Count; i++)
      {
        
    Console.WriteLine("Lottery Number " + i + " is " + tryYourLuck.Results[i]);
      }

      // Change it so we win!
      tryYourLuck.Results[0]=29;

      //The above line gives // Error 26 // Property or indexer
      // 'System.Collections.ObjectModel. ReadOnlyCollection<int>.this[int]'
      // cannot be assigned to -- it is read only

    Discussion

    The main advantage ReadOnlyCollection provides is the flexibility to use it with any collection that supports IList or IList<T>as an interface. ReadOnlyCollection can be used to wrap a regular array like this:

      int[] items = {0, 1, 2 };
      ReadOnlyCollection<int> readOnlyItems =
          new ReadOnlyCollection<int>(items);

    This provides a way to standardize the read-only properties on classes to make it easier for consumers of the class to recognize which properties are read-only simply by the return type.

    See Also

    The “ReadOnlyCollection” topic in the MSDN documentation.

    Please check back next week for the conclusion of this article.


    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

    - Coding a CRC-Generating Algorithm in C
    - 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#





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek