Export (0) Print
Expand All

CollectionBase Class

Provides the abstract base class for a strongly typed collection.

System.Object
  System.Collections.CollectionBase
    More...

Namespace:  System.Collections
Assembly:  mscorlib (in mscorlib.dll)

[SerializableAttribute]
[ComVisibleAttribute(true)]
public abstract class CollectionBase : IList, 
	ICollection, IEnumerable

The CollectionBase type exposes the following members.

  NameDescription
Protected methodSupported by the XNA FrameworkCollectionBase()Initializes a new instance of the CollectionBase class with the default initial capacity.
Protected methodSupported by the XNA FrameworkCollectionBase(Int32)Initializes a new instance of the CollectionBase class with the specified capacity.
Top

  NameDescription
Public propertySupported by the XNA FrameworkCapacityGets or sets the number of elements that the CollectionBase can contain.
Public propertySupported by the XNA FrameworkCountGets the number of elements contained in the CollectionBase instance. This property cannot be overridden.
Protected propertySupported by the XNA FrameworkInnerListGets an ArrayList containing the list of elements in the CollectionBase instance.
Protected propertySupported by the XNA FrameworkListGets an IList containing the list of elements in the CollectionBase instance.
Top

  NameDescription
Public methodSupported by the XNA FrameworkClearRemoves all objects from the CollectionBase instance. This method cannot be overridden.
Public methodSupported by the XNA FrameworkEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by the XNA FrameworkGetEnumeratorReturns an enumerator that iterates through the CollectionBase instance.
Public methodSupported by the XNA FrameworkGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodSupported by the XNA FrameworkGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkOnClearPerforms additional custom processes when clearing the contents of the CollectionBase instance.
Protected methodSupported by the XNA FrameworkOnClearCompletePerforms additional custom processes after clearing the contents of the CollectionBase instance.
Protected methodSupported by the XNA FrameworkOnInsertPerforms additional custom processes before inserting a new element into the CollectionBase instance.
Protected methodSupported by the XNA FrameworkOnInsertCompletePerforms additional custom processes after inserting a new element into the CollectionBase instance.
Protected methodSupported by the XNA FrameworkOnRemovePerforms additional custom processes when removing an element from the CollectionBase instance.
Protected methodSupported by the XNA FrameworkOnRemoveCompletePerforms additional custom processes after removing an element from the CollectionBase instance.
Protected methodSupported by the XNA FrameworkOnSetPerforms additional custom processes before setting a value in the CollectionBase instance.
Protected methodSupported by the XNA FrameworkOnSetCompletePerforms additional custom processes after setting a value in the CollectionBase instance.
Protected methodSupported by the XNA FrameworkOnValidatePerforms additional custom processes when validating a value.
Public methodSupported by the XNA FrameworkRemoveAtRemoves the element at the specified index of the CollectionBase instance. This method is not overridable.
Public methodSupported by the XNA FrameworkToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Public Extension MethodAsParallelEnables parallelization of a query. (Defined by ParallelEnumerable.)
Public Extension MethodAsQueryableConverts an IEnumerable to an IQueryable. (Defined by Queryable.)
Public Extension MethodSupported by the XNA FrameworkCast<TResult>Casts the elements of an IEnumerable to the specified type. (Defined by Enumerable.)
Public Extension MethodSupported by the XNA FrameworkOfType<TResult>Filters the elements of an IEnumerable based on a specified type. (Defined by Enumerable.)
Top

  NameDescription
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkICollection.CopyToCopies the entire CollectionBase to a compatible one-dimensional Array, starting at the specified index of the target array.
Explicit interface implemetationPrivate propertySupported by the XNA FrameworkICollection.IsSynchronizedGets a value indicating whether access to the CollectionBase is synchronized (thread safe).
Explicit interface implemetationPrivate propertySupported by the XNA FrameworkICollection.SyncRootGets an object that can be used to synchronize access to the CollectionBase.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIList.AddAdds an object to the end of the CollectionBase.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIList.ContainsDetermines whether the CollectionBase contains a specific element.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIList.IndexOfSearches for the specified Object and returns the zero-based index of the first occurrence within the entire CollectionBase.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIList.InsertInserts an element into the CollectionBase at the specified index.
Explicit interface implemetationPrivate propertySupported by the XNA FrameworkIList.IsFixedSizeGets a value indicating whether the CollectionBase has a fixed size.
Explicit interface implemetationPrivate propertySupported by the XNA FrameworkIList.IsReadOnlyGets a value indicating whether the CollectionBase is read-only.
Explicit interface implemetationPrivate propertySupported by the XNA FrameworkIList.ItemGets or sets the element at the specified index.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIList.RemoveRemoves the first occurrence of a specific object from the CollectionBase.
Top

A CollectionBase instance is always modifiable. See ReadOnlyCollectionBase for a read-only version of this class.

The capacity of a CollectionBase is the number of elements the CollectionBase can hold. As elements are added to a CollectionBase, the capacity is automatically increased as required through reallocation. The capacity can be decreased by setting the Capacity property explicitly.

Notes to Implementers

This base class is provided to make it easier for implementers to create a strongly typed custom collection. Implementers are encouraged to extend this base class instead of creating their own.

The following code example implements the CollectionBase class and uses that implementation to create a collection of Int16 objects.

using System;
using System.Collections;

public class Int16Collection : CollectionBase  {

   public Int16 this[ int index ]  {
      get  {
         return( (Int16) List[index] );
      }
      set  {
         List[index] = value;
      }
   }

   public int Add( Int16 value )  {
      return( List.Add( value ) );
   }

   public int IndexOf( Int16 value )  {
      return( List.IndexOf( value ) );
   }

   public void Insert( int index, Int16 value )  {
      List.Insert( index, value );
   }

   public void Remove( Int16 value )  {
      List.Remove( value );
   }

   public bool Contains( Int16 value )  {
      // If value is not of type Int16, this will return false. 
      return( List.Contains( value ) );
   }

   protected override void OnInsert( int index, Object value )  {
      // Insert additional code to be run only when inserting values.
   }

   protected override void OnRemove( int index, Object value )  {
      // Insert additional code to be run only when removing values.
   }

   protected override void OnSet( int index, Object oldValue, Object newValue )  {
      // Insert additional code to be run only when setting values.
   }

   protected override void OnValidate( Object value )  {
      if ( value.GetType() != typeof(System.Int16) )
         throw new ArgumentException( "value must be of type Int16.", "value" );
   }

}


public class SamplesCollectionBase  {

   public static void Main()  {

      // Create and initialize a new CollectionBase.
      Int16Collection myI16 = new Int16Collection();

      // Add elements to the collection.
      myI16.Add( (Int16) 1 );
      myI16.Add( (Int16) 2 );
      myI16.Add( (Int16) 3 );
      myI16.Add( (Int16) 5 );
      myI16.Add( (Int16) 7 );

      // Display the contents of the collection using foreach. This is the preferred method.
      Console.WriteLine( "Contents of the collection (using foreach):" );
      PrintValues1( myI16 );

      // Display the contents of the collection using the enumerator.
      Console.WriteLine( "Contents of the collection (using enumerator):" );
      PrintValues2( myI16 );

      // Display the contents of the collection using the Count property and the Item property.
      Console.WriteLine( "Initial contents of the collection (using Count and Item):" );
      PrintIndexAndValues( myI16 );

      // Search the collection with Contains and IndexOf.
      Console.WriteLine( "Contains 3: {0}", myI16.Contains( 3 ) );
      Console.WriteLine( "2 is at index {0}.", myI16.IndexOf( 2 ) );
      Console.WriteLine();

      // Insert an element into the collection at index 3.
      myI16.Insert( 3, (Int16) 13 );
      Console.WriteLine( "Contents of the collection after inserting at index 3:" );
      PrintIndexAndValues( myI16 );

      // Get and set an element using the index.
      myI16[4] = 123;
      Console.WriteLine( "Contents of the collection after setting the element at index 4 to 123:" );
      PrintIndexAndValues( myI16 );

      // Remove an element from the collection.
      myI16.Remove( (Int16) 2 );

      // Display the contents of the collection using the Count property and the Item property.
      Console.WriteLine( "Contents of the collection after removing the element 2:" );
      PrintIndexAndValues( myI16 );

   }

   // Uses the Count property and the Item property. 
   public static void PrintIndexAndValues( Int16Collection myCol )  {
      for ( int i = 0; i < myCol.Count; i++ )
         Console.WriteLine( "   [{0}]:   {1}", i, myCol[i] );
      Console.WriteLine();
   }

   // Uses the foreach statement which hides the complexity of the enumerator. 
   // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. 
   public static void PrintValues1( Int16Collection myCol )  {
      foreach ( Int16 i16 in myCol )
         Console.WriteLine( "   {0}", i16 );
      Console.WriteLine();
   }

   // Uses the enumerator.  
   // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. 
   public static void PrintValues2( Int16Collection myCol )  {
      System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator();
      while ( myEnumerator.MoveNext() )
         Console.WriteLine( "   {0}", myEnumerator.Current );
      Console.WriteLine();
   }
}


/* 
This code produces the following output.

Contents of the collection (using foreach):
   1
   2
   3
   5
   7

Contents of the collection (using enumerator):
   1
   2
   3
   5
   7

Initial contents of the collection (using Count and Item):
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   5
   [4]:   7

Contains 3: True
2 is at index 1.

Contents of the collection after inserting at index 3:
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   13
   [4]:   5
   [5]:   7

Contents of the collection after setting the element at index 4 to 123:
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   13
   [4]:   123
   [5]:   7

Contents of the collection after removing the element 2:
   [0]:   1
   [1]:   3
   [2]:   13
   [3]:   123
   [4]:   7

*/

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

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 CollectionBase, but derived classes can create their own synchronized versions of the CollectionBase 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.

System.Object
  System.Collections.CollectionBase
    System.CodeDom.CodeAttributeArgumentCollection
    System.CodeDom.CodeAttributeDeclarationCollection
    System.CodeDom.CodeCatchClauseCollection
    System.CodeDom.CodeCommentStatementCollection
    System.CodeDom.CodeDirectiveCollection
    System.CodeDom.CodeExpressionCollection
    System.CodeDom.CodeNamespaceCollection
    System.CodeDom.CodeParameterDeclarationExpressionCollection
    System.CodeDom.CodeStatementCollection
    System.CodeDom.CodeTypeDeclarationCollection
    System.CodeDom.CodeTypeMemberCollection
    System.CodeDom.CodeTypeParameterCollection
    System.CodeDom.CodeTypeReferenceCollection
    System.CodeDom.Compiler.CompilerErrorCollection
    System.ComponentModel.Design.Data.DataSourceDescriptorCollection
    System.ComponentModel.Design.Data.DataSourceGroupCollection
    System.ComponentModel.Design.DesignerActionItemCollection
    System.ComponentModel.Design.DesignerActionListCollection
    System.ComponentModel.Design.DesignerVerbCollection
    System.Configuration.Install.InstallerCollection
    System.Data.SqlClient.SqlBulkCopyColumnMappingCollection
    System.Diagnostics.CounterCreationDataCollection
    System.Diagnostics.EventLogPermissionEntryCollection
    System.Diagnostics.PerformanceCounterPermissionEntryCollection
    System.DirectoryServices.ActiveDirectory.ActiveDirectorySchemaClassCollection
    System.DirectoryServices.ActiveDirectory.ActiveDirectorySchemaPropertyCollection
    System.DirectoryServices.ActiveDirectory.ActiveDirectorySiteCollection
    System.DirectoryServices.ActiveDirectory.ActiveDirectorySiteLinkCollection
    System.DirectoryServices.ActiveDirectory.ActiveDirectorySubnetCollection
    System.DirectoryServices.ActiveDirectory.DirectoryServerCollection
    System.DirectoryServices.DirectoryServicesPermissionEntryCollection
    System.DirectoryServices.PropertyValueCollection
    System.DirectoryServices.Protocols.DirectoryAttribute
    System.DirectoryServices.Protocols.DirectoryAttributeCollection
    System.DirectoryServices.Protocols.DirectoryAttributeModificationCollection
    System.DirectoryServices.Protocols.DirectoryControlCollection
    System.Messaging.AccessControlList
    System.Messaging.MessageQueuePermissionEntryCollection
    System.Security.Cryptography.X509Certificates.X509CertificateCollection
    System.ServiceProcess.ServiceControllerPermissionEntryCollection
    System.Web.ParserErrorCollection
    System.Web.Services.Description.BasicProfileViolationCollection
    System.Web.Services.Description.MimePartCollection
    System.Web.Services.Description.MimeTextMatchCollection
    System.Web.Services.Description.ServiceDescriptionBaseCollection
    System.Web.Services.Description.WebReferenceCollection
    System.Web.Services.Discovery.DiscoveryClientResultCollection
    System.Web.Services.Discovery.DiscoveryReferenceCollection
    System.Web.Services.Protocols.SoapHeaderCollection
    System.Web.UI.WebControls.EmbeddedMailObjectsCollection
    System.Web.UI.WebControls.RoleGroupCollection
    System.Web.UI.WebControls.WebParts.ProxyWebPartConnectionCollection
    System.Web.UI.WebControls.WebParts.WebPartConnectionCollection
    System.Web.UI.WebControls.WebParts.WebPartDisplayModeCollection
    System.Web.UI.WebControls.WebParts.WebPartTransformerCollection
    System.Windows.Documents.LinkTargetCollection
    System.Windows.Forms.Design.Behavior.BehaviorServiceAdornerCollection
    System.Windows.Forms.Design.Behavior.GlyphCollection
    System.Xml.Schema.XmlSchemaObjectCollection
    System.Xml.Serialization.Advanced.SchemaImporterExtensionCollection
    System.Xml.Serialization.XmlAnyElementAttributes
    System.Xml.Serialization.XmlArrayItemAttributes
    System.Xml.Serialization.XmlElementAttributes
    System.Xml.Serialization.XmlSchemas
Show:
© 2014 Microsoft