Export (0) Print
Expand All

NameObjectCollectionBase Class

Provides the abstract base class for a collection of associated String keys and Object values that can be accessed either with the key or with the index.

Namespace: System.Collections.Specialized
Assembly: System (in system.dll)

[SerializableAttribute] 
public abstract class NameObjectCollectionBase : ICollection, IEnumerable, ISerializable, 
	IDeserializationCallback
/** @attribute SerializableAttribute() */ 
public abstract class NameObjectCollectionBase implements ICollection, IEnumerable, 
	ISerializable, IDeserializationCallback
SerializableAttribute 
public abstract class NameObjectCollectionBase implements ICollection, IEnumerable, 
	ISerializable, IDeserializationCallback
Not applicable.

The underlying structure for this class is a hash table.

Each element is a key/value pair.

The capacity of a NameObjectCollectionBase is the number of elements the NameObjectCollectionBase can hold. As elements are added to a NameObjectCollectionBase, the capacity is automatically increased as required through reallocation.

The hash code provider dispenses hash codes for keys in the NameObjectCollectionBase instance. The default hash code provider is the CaseInsensitiveHashCodeProvider.

The comparer determines whether two keys are equal. The default comparer is the CaseInsensitiveComparer.

In .NET Framework version 1.0, this class uses culture-sensitive string comparisons. However, in .NET Framework version 1.1 and later, this class uses CultureInfo.InvariantCulture when comparing strings. For more information about how culture affects comparisons and sorting, see Comparing and Sorting Data for a Specific CultureComparing and Sorting Data for a Specific Cultureand Performing Culture-Insensitive String Operations.

a null reference (Nothing in Visual Basic) is allowed as a key or as a value.

Caution noteCaution:

The BaseGet method does not distinguish between a null reference (Nothing in Visual Basic) which is returned because the specified key is not found and a null reference (Nothing in Visual Basic) which is returned because the value associated with the key is a null reference (Nothing in Visual Basic).

The following code example shows how to implement and use the NameObjectCollectionBase class.

using System;
using System.Collections;
using System.Collections.Specialized;

public class MyCollection : NameObjectCollectionBase
{
   // Creates an empty collection.
   public MyCollection()  {
   }

   // Adds elements from an IDictionary into the new collection.
   public MyCollection( IDictionary d, Boolean bReadOnly )  {
      foreach ( DictionaryEntry de in d )  {
         this.BaseAdd( (String) de.Key, de.Value );
      }
      this.IsReadOnly = bReadOnly;
   }

   // Gets a key-and-value pair (DictionaryEntry) using an index.
   public DictionaryEntry this[ int index ]  {
      get  {
          return ( new DictionaryEntry( 
              this.BaseGetKey(index), this.BaseGet(index) ) );
      }
   }

   // Gets or sets the value associated with the specified key.
   public Object this[ String key ]  {
      get  {
         return( this.BaseGet( key ) );
      }
      set  {
         this.BaseSet( key, value );
      }
   }

   // Gets a String array that contains all the keys in the collection.
   public String[] AllKeys  {
      get  {
         return( this.BaseGetAllKeys() );
      }
   }

   // Gets an Object array that contains all the values in the collection.
   public Array AllValues  {
      get  {
         return( this.BaseGetAllValues() );
      }
   }

   // Gets a String array that contains all the values in the collection.
   public String[] AllStringValues  {
      get  {
         return( (String[]) this.BaseGetAllValues( typeof( string ) ));
      }
   }

   // Gets a value indicating if the collection contains keys that are not null.
   public Boolean HasKeys  {
      get  {
         return( this.BaseHasKeys() );
      }
   }

   // Adds an entry to the collection.
   public void Add( String key, Object value )  {
      this.BaseAdd( key, value );
   }

   // Removes an entry with the specified key from the collection.
   public void Remove( String key )  {
      this.BaseRemove( key );
   }

   // Removes an entry in the specified index from the collection.
   public void Remove( int index )  {
      this.BaseRemoveAt( index );
   }

   // Clears all the elements in the collection.
   public void Clear()  {
      this.BaseClear();
   }

}

public class SamplesNameObjectCollectionBase  {

   public static void Main()  {

      // Creates and initializes a new MyCollection that is read-only.
      IDictionary d = new ListDictionary();
      d.Add( "red", "apple" );
      d.Add( "yellow", "banana" );
      d.Add( "green", "pear" );
      MyCollection myROCol = new MyCollection( d, true );

      // Tries to add a new item.
      try  {
         myROCol.Add( "blue", "sky" );
      }
      catch ( NotSupportedException e )  {
         Console.WriteLine( e.ToString() );
      }

      // Displays the keys and values of the MyCollection.
      Console.WriteLine( "Read-Only Collection:" );
      PrintKeysAndValues( myROCol );


      // Creates and initializes an empty MyCollection that is writable.
      MyCollection myRWCol = new MyCollection();

      // Adds new items to the collection.
      myRWCol.Add( "purple", "grape" );
      myRWCol.Add( "orange", "tangerine" );
      myRWCol.Add( "black", "berries" );
      Console.WriteLine( "Writable Collection (after adding values):" );
      PrintKeysAndValues( myRWCol );

      // Changes the value of one element.
      myRWCol["orange"] = "grapefruit";
      Console.WriteLine( "Writable Collection (after changing one value):" );
      PrintKeysAndValues( myRWCol );

      // Removes one item from the collection.
      myRWCol.Remove( "black" );
      Console.WriteLine( "Writable Collection (after removing one value):" );
      PrintKeysAndValues( myRWCol );

      // Removes all elements from the collection.
      myRWCol.Clear();
      Console.WriteLine( "Writable Collection (after clearing the collection):" );
      PrintKeysAndValues( myRWCol );

   }

   // Prints the indexes, keys, and values.
   public static void PrintKeysAndValues( MyCollection myCol )  {
      for ( int i = 0; i < myCol.Count; i++ )  {
         Console.WriteLine( "[{0}] : {1}, {2}", i, myCol[i].Key, myCol[i].Value );
      }
   }

   // Prints the keys and values using AllKeys.
   public static void PrintKeysAndValues2( MyCollection myCol )  {
      foreach ( String s in myCol.AllKeys )  {
         Console.WriteLine( "{0}, {1}", s, myCol[s] );
      }
   }
}


/*
This code produces the following output.

System.NotSupportedException: Collection is read-only.
   at System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String name, Object value)
   at SamplesNameObjectCollectionBase.Main()
Read-Only Collection:
[0] : red, apple
[1] : yellow, banana
[2] : green, pear
Writable Collection (after adding values):
[0] : purple, grape
[1] : orange, tangerine
[2] : black, berries
Writable Collection (after changing one value):
[0] : purple, grape
[1] : orange, grapefruit
[2] : black, berries
Writable Collection (after removing one value):
[0] : purple, grape
[1] : orange, grapefruit
Writable Collection (after clearing the collection):

*/

import System.* ;
import System.Collections.* ;
import System.Collections.Specialized.* ;

public class MyCollection extends NameObjectCollectionBase
{
    private DictionaryEntry _de =  new DictionaryEntry();

    // Creates an empty collection.
    public MyCollection() 
    {
    } //MyCollection

    // Adds elements from an IDictionary into the new collection.
    public MyCollection(IDictionary d, boolean bReadOnly) 
    {
        IDictionaryEnumerator objEnum = d.GetEnumerator();

        while (objEnum.MoveNext()) {        
            DictionaryEntry de = (DictionaryEntry)objEnum.get_Current();
            this.BaseAdd(((String)(de.get_Key())), de.get_Value());
        } 

        this.set_IsReadOnly(bReadOnly);        
    } //MyCollection

    // Gets a key-and-value pair (DictionaryEntry) using an index.
    /** @property 
     */
    public DictionaryEntry get_Item(int index)
    {
        _de.set_Key(this.BaseGetKey(index));
        _de.set_Value(this.BaseGet(index));
        return _de ;
    } //get_Item

    // Gets or sets the value associated with the specified key.
    /** @property 
     */
    public Object get_Item(String key)
    {
        return this.BaseGet(key) ;
    } //get_Item

    /** @property 
     */
    public void set_Item(String key, Object value)
    {
        this.BaseSet(key, value);
    } //set_Item

    // Gets a String array that contains all the keys in the collection.
    /** @property 
     */
    public String[] get_AllKeys()
    {
        return this.BaseGetAllKeys() ;
    } //get_AllKeys

    // Gets an Object array that contains all the values in the collection.
    /** @property 
     */
    public Array get_AllValues()
    {
        return this.BaseGetAllValues() ;
    } //get_AllValues

    // Gets a String array that contains all the values in the collection.
    /** @property 
     */
    public String[] get_AllStringValues()
    {
        return((String[])(this.BaseGetAllValues(Type.GetType("String")))) ;
    } //get_AllStringValues

    // Gets a value indicating if the collection contains keys that are not null
    /** @property
     */
    public Boolean get_HasKeys()
    {
        return new Boolean(this.BaseHasKeys()) ;
    } //get_HasKeys


    // Adds an entry to the collection.
    public void Add(String key, Object value) 
    {
        this.BaseAdd(key, value);
    } //Add

    // Removes an entry with the specified key from the collection.
    public void Remove(String key) 
    {
        this.BaseRemove(key);
    } //Remove

    // Removes an entry in the specified index from the collection.
    public void Remove(int index) 
    {
        this.BaseRemoveAt(index);
    } //Remove

    // Clears all the elements in the collection.
    public void Clear() 
    {
        this.BaseClear();
    } //Clear
} //MyCollection

public class SamplesNameObjectCollectionBase 
{
    public static void main(String[] args)
    {
        // Creates and initializes a new MyCollection that is read-only.
        IDictionary d = new ListDictionary();
        d.Add("red", "apple");
        d.Add("yellow", "banana");
        d.Add("green", "pear");
        MyCollection myROCol = new MyCollection(d, true);
        
        // Tries to add a new item.
        try {
            myROCol.Add("blue", "sky");
        } 
        catch (NotSupportedException e) {        
            Console.WriteLine(e.ToString());
        } 
        
        // Displays the keys and values of the MyCollection.
        Console.WriteLine("Read-Only Collection:");
        PrintKeysAndValues(myROCol);        
        
        // Creates and initializes an empty MyCollection that is writable.
        MyCollection myRWCol =  new MyCollection();
        
        // Adds new items to the collection.
        myRWCol.Add("purple", "grape");
        myRWCol.Add("orange", "tangerine");
        myRWCol.Add("black", "berries");
        Console.WriteLine("Writable Collection (after adding values):");
        PrintKeysAndValues(myRWCol);
        
        // Changes the value of one element.
        myRWCol.set_Item( "orange" , "grapefruit" );
        Console.WriteLine("Writable Collection (after changing one value):");
        PrintKeysAndValues(myRWCol);
        
        // Removes one item from the collection.
        myRWCol.Remove("black");
        Console.WriteLine("Writable Collection (after removing one value):");
        PrintKeysAndValues(myRWCol);
        
        // Removes all elements from the collection.
        myRWCol.Clear();
        Console.WriteLine("Writable Collection (after clearing the"
            + " collection):");
        PrintKeysAndValues(myRWCol);
    } //main

    // Prints the indexes, keys, and values.
    public static void PrintKeysAndValues(MyCollection myCol)
    {

        for (int i=0; i < myCol.get_Count(); i++) {        
            Console.WriteLine("[{0}] : {1}, {2}",System.Convert.ToString(i),
                myCol.get_Item(i).get_Key(), myCol.get_Item(i).get_Value());
        } 
    } //PrintKeysAndValues

    // Prints the keys and values using AllKeys.
    public static void PrintKeysAndValues2(MyCollection myCol)
    {
        String str = new String();

        for (int iCtr = 0; iCtr < myCol.get_Count(); iCtr++) {        
            str = myCol.get_AllKeys()[iCtr];
            Console.WriteLine("{0} , {1}", str, 
                (myCol.get_Item(str)).ToString());
        } 
    } //PrintKeysAndValues2
} //SamplesNameObjectCollectionBase

/*
This code produces the following output.

System.NotSupportedException: Collection is read-only.
   at System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String name, Object value)
   at SamplesNameObjectCollectionBase.main(String[] args)
Read-Only Collection:
[0] : red, apple
[1] : yellow, banana
[2] : green, pear
Writable Collection (after adding values):
[0] : purple, grape
[1] : orange, tangerine
[2] : black, berries
Writable Collection (after changing one value):
[0] : purple, grape
[1] : orange, grapefruit
[2] : black, berries
Writable Collection (after removing one value):
[0] : purple, grape
[1] : orange, grapefruit
Writable Collection (after clearing the collection):

*/

System.Object
  System.Collections.Specialized.NameObjectCollectionBase
     Derived Classes

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

This implementation does not provide a synchronized (thread safe) wrapper for a NameObjectCollectionBase, but derived classes can create their own synchronized versions of the NameObjectCollectionBase using the SyncRoot property.

Enumerating through a collection is intrinsically not a thread safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0

Community Additions

ADD
Show:
© 2014 Microsoft