CollectionBase Class

 

Provides the abstract base class for a strongly typed collection.

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

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

<SerializableAttribute>
<ComVisibleAttribute(True)>
Public MustInherit Class CollectionBase
	Implements IList, ICollection, IEnumerable

NameDescription
System_CAPS_protmethodCollectionBase()

Initializes a new instance of the CollectionBase class with the default initial capacity.

System_CAPS_protmethodCollectionBase(Int32)

Initializes a new instance of the CollectionBase class with the specified capacity.

NameDescription
System_CAPS_pubpropertyCapacity

Gets or sets the number of elements that the CollectionBase can contain.

System_CAPS_pubpropertyCount

Gets the number of elements contained in the CollectionBase instance. This property cannot be overridden.

System_CAPS_protpropertyInnerList

Gets an ArrayList containing the list of elements in the CollectionBase instance.

System_CAPS_protpropertyList

Gets an IList containing the list of elements in the CollectionBase instance.

NameDescription
System_CAPS_pubmethodClear()

Removes all objects from the CollectionBase instance. This method cannot be overridden.

System_CAPS_pubmethodEquals(Object)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_protmethodFinalize()

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)

System_CAPS_pubmethodGetEnumerator()

Returns an enumerator that iterates through the CollectionBase instance.

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_protmethodMemberwiseClone()

Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_protmethodOnClear()

Performs additional custom processes when clearing the contents of the CollectionBase instance.

System_CAPS_protmethodOnClearComplete()

Performs additional custom processes after clearing the contents of the CollectionBase instance.

System_CAPS_protmethodOnInsert(Int32, Object)

Performs additional custom processes before inserting a new element into the CollectionBase instance.

System_CAPS_protmethodOnInsertComplete(Int32, Object)

Performs additional custom processes after inserting a new element into the CollectionBase instance.

System_CAPS_protmethodOnRemove(Int32, Object)

Performs additional custom processes when removing an element from the CollectionBase instance.

System_CAPS_protmethodOnRemoveComplete(Int32, Object)

Performs additional custom processes after removing an element from the CollectionBase instance.

System_CAPS_protmethodOnSet(Int32, Object, Object)

Performs additional custom processes before setting a value in the CollectionBase instance.

System_CAPS_protmethodOnSetComplete(Int32, Object, Object)

Performs additional custom processes after setting a value in the CollectionBase instance.

System_CAPS_protmethodOnValidate(Object)

Performs additional custom processes when validating a value.

System_CAPS_pubmethodRemoveAt(Int32)

Removes the element at the specified index of the CollectionBase instance. This method is not overridable.

System_CAPS_pubmethodToString()

Returns a string that represents the current object.(Inherited from Object.)

NameDescription
System_CAPS_pubinterfaceSystem_CAPS_privmethodICollection.CopyTo(Array, Int32)

Copies the entire CollectionBase to a compatible one-dimensional Array, starting at the specified index of the target array.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIList.Add(Object)

Adds an object to the end of the CollectionBase.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIList.Contains(Object)

Determines whether the CollectionBase contains a specific element.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIList.IndexOf(Object)

Searches for the specified Object and returns the zero-based index of the first occurrence within the entire CollectionBase.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIList.Insert(Int32, Object)

Inserts an element into the CollectionBase at the specified index.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIList.Remove(Object)

Removes the first occurrence of a specific object from the CollectionBase.

System_CAPS_pubinterfaceSystem_CAPS_privpropertyICollection.IsSynchronized

Gets a value indicating whether access to the CollectionBase is synchronized (thread safe).

System_CAPS_pubinterfaceSystem_CAPS_privpropertyICollection.SyncRoot

Gets an object that can be used to synchronize access to the CollectionBase.

System_CAPS_pubinterfaceSystem_CAPS_privpropertyIList.IsFixedSize

Gets a value indicating whether the CollectionBase has a fixed size.

System_CAPS_pubinterfaceSystem_CAPS_privpropertyIList.IsReadOnly

Gets a value indicating whether the CollectionBase is read-only.

System_CAPS_pubinterfaceSystem_CAPS_privpropertyIList.Item(Int32)

Gets or sets the element at the specified index.

NameDescription
System_CAPS_pubmethodAsParallel()

Overloaded. Enables parallelization of a query.(Defined by ParallelEnumerable.)

System_CAPS_pubmethodAsQueryable()

Overloaded. Converts an IEnumerable to an IQueryable.(Defined by Queryable.)

System_CAPS_pubmethodCast(Of TResult)()

Casts the elements of an IEnumerable to the specified type.(Defined by Enumerable.)

System_CAPS_pubmethodOfType(Of TResult)()

Filters the elements of an IEnumerable based on a specified type.(Defined by Enumerable.)

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.

Imports System
Imports System.Collections


Public Class Int16Collection
   Inherits CollectionBase


   Default Public Property Item(index As Integer) As Int16
      Get
         Return CType(List(index), Int16)
      End Get
      Set
         List(index) = value
      End Set
   End Property


   Public Function Add(value As Int16) As Integer
      Return List.Add(value)
   End Function 'Add

   Public Function IndexOf(value As Int16) As Integer
      Return List.IndexOf(value)
   End Function 'IndexOf


   Public Sub Insert(index As Integer, value As Int16)
      List.Insert(index, value)
   End Sub 'Insert


   Public Sub Remove(value As Int16)
      List.Remove(value)
   End Sub 'Remove


   Public Function Contains(value As Int16) As Boolean
      ' If value is not of type Int16, this will return false.
      Return List.Contains(value)
   End Function 'Contains


   Protected Overrides Sub OnInsert(index As Integer, value As Object)
      ' Insert additional code to be run only when inserting values.
   End Sub 'OnInsert


   Protected Overrides Sub OnRemove(index As Integer, value As Object)
      ' Insert additional code to be run only when removing values.
   End Sub 'OnRemove


   Protected Overrides Sub OnSet(index As Integer, oldValue As Object, newValue As Object)
      ' Insert additional code to be run only when setting values.
   End Sub 'OnSet


   Protected Overrides Sub OnValidate(value As Object)
      If Not GetType(System.Int16).IsAssignableFrom(value.GetType()) Then
         Throw New ArgumentException("value must be of type Int16.", "value")
      End If
   End Sub 'OnValidate 

End Class 'Int16Collection


Public Class SamplesCollectionBase

   Public Shared Sub Main()

      ' Creates and initializes a new CollectionBase.
      Dim myI16 As New Int16Collection()

      ' Adds elements to the collection.
      myI16.Add( 1 )
      myI16.Add( 2 )
      myI16.Add( 3 )
      myI16.Add( 5 )
      myI16.Add( 7 )

      ' Display the contents of the collection using For Each. This is the preferred method.
      Console.WriteLine("Contents of the collection (using For Each):")
      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)

      ' Searches 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()

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

      ' Gets and sets 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)

      ' Removes an element from the collection.
      myI16.Remove(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)

    End Sub 'Main


    ' Uses the Count property and the Item property.
    Public Shared Sub PrintIndexAndValues(myCol As Int16Collection)
      Dim i As Integer
      For i = 0 To myCol.Count - 1
          Console.WriteLine("   [{0}]:   {1}", i, myCol(i))
      Next i
      Console.WriteLine()
    End Sub 'PrintIndexAndValues


    ' Uses the For Each statement which hides the complexity of the enumerator.
    ' NOTE: The For Each statement is the preferred way of enumerating the contents of a collection.
    Public Shared Sub PrintValues1(myCol As Int16Collection)
      Dim i16 As Int16
      For Each i16 In  myCol
          Console.WriteLine("   {0}", i16)
      Next i16
      Console.WriteLine()
    End Sub 'PrintValues1


    ' Uses the enumerator. 
    ' NOTE: The For Each statement is the preferred way of enumerating the contents of a collection.
    Public Shared Sub PrintValues2(myCol As Int16Collection)
      Dim myEnumerator As System.Collections.IEnumerator = myCol.GetEnumerator()
      While myEnumerator.MoveNext()
          Console.WriteLine("   {0}", myEnumerator.Current)
      End While
      Console.WriteLine()
    End Sub 'PrintValues2

End Class 'SamplesCollectionBase


'This code produces the following output.
'
'Contents of the collection (using For Each):
'   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

Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1

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.

Return to top
Show: