ConfigurationCollectionAttribute Class

Note: This class is new in the .NET Framework version 2.0.

Declaratively instructs the .NET Framework to instantiate a configuration element collection. This class cannot be inherited.

Namespace: System.Configuration
Assembly: System.Configuration (in system.configuration.dll)

<AttributeUsageAttribute(AttributeTargets.Class Or AttributeTargets.Property)> _
Public NotInheritable Class ConfigurationCollectionAttribute
	Inherits Attribute
Dim instance As ConfigurationCollectionAttribute

/** @attribute AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Property) */ 
public final class ConfigurationCollectionAttribute extends Attribute
public final class ConfigurationCollectionAttribute extends Attribute

You use the ConfigurationCollectionAttribute attribute to decorate a ConfigurationElementCollection element. This instructs the .NET Framework to instantiate the collection and to initialize it using your custom ConfigurationElement values.


The simplest way of creating a custom configuration element is to use the attributed (declarative) model. You declare the elements and decorate them with the ConfigurationCollectionAttribute attribute. For each element marked with this attribute, the .NET Framework uses reflection to read the decorating parameters and create a related ConfigurationElementCollection instance. You can also use the programmatic model. In this case it is your responsibility to declare the custom public collection but also to override the ConfigurationElementCollection member and return the properties collection.

The .NET Framework configuration system provides attribute types that you can use during the creation of custom configuration elements. There are two kinds of attributes.

The following example shows how to use the ConfigurationCollectionAttribute.

The example contains four classes. The class TestingConfigurationCollectionAttribute creates a custom configuration section containing a collection of elements. The remaining three classes are used to create the custom section. The custom section type UrlsSection contains an Urls property. This property is a custom collection of type UrlsCollection containing custom elements of type UrlConfigElement. Note that the key for this example to work is the Urls property, decorated with the ConfigurationCollectionAttribute.

Imports System
Imports System.Configuration

' Define a property section named <urls>
' containing a UrlsCollection collection of 
' UrlConfigElement elements.
' This section requires the definition of UrlsCollection and
' UrlsConfigElement types.

Public Class UrlsSection
   Inherits ConfigurationSection
   ' Declare the collection element.
   Private url As UrlConfigElement
   Public Sub New()
      ' Create a collection element.
      ' The property values assigned to 
      ' this instance are provided
      ' by the ConfigurationProperty attributes
      ' associated wiht the UrlConfigElement 
      ' properties.
      url = New UrlConfigElement()
   End Sub 'New
   ' Declare the urls collection property.
   ' Note: the "IsDefaultCollection = false" instructs 
   '.NET Framework to build a nested section of 
   'the kind <urls> ...</urls>.
    <ConfigurationProperty("urls", _
    IsDefaultCollection:=False), _
    ConfigurationCollection(GetType(UrlsCollection), _
    AddItemName:="addUrl", _
    ClearItemsName:="clearUrls", _
    RemoveItemName:="RemoveUrl")> _
    Public ReadOnly Property Urls() As UrlsCollection
            Dim urlCollection As UrlsCollection = _
            CType(MyBase.Item("urls"), UrlsCollection)
            Return urlCollection
        End Get
    End Property

End Class 'UrlsSection 

' Define the UrlsCollection that will contain the 
' UrlsConfigElement elements.
Public Class UrlsCollection
   Inherits ConfigurationElementCollection
   Public Sub New()
        Dim url As UrlConfigElement = _
        CType(CreateNewElement(), UrlConfigElement)
   End Sub 'New
    Public Overrides ReadOnly Property CollectionType() _
    As ConfigurationElementCollectionType
            Return ConfigurationElementCollectionType.AddRemoveClearMap
        End Get
    End Property
    Protected Overrides Function CreateNewElement() _
    As ConfigurationElement
        Return New UrlConfigElement()
    End Function 'CreateNewElement
    Protected Overrides Function GetElementKey(ByVal element _
    As ConfigurationElement) As [Object]
        Return CType(element, UrlConfigElement).Name
    End Function 'GetElementKey
    Default Public Shadows Property Item( _
    ByVal index As Integer) As UrlConfigElement
            Return CType(BaseGet(index), UrlConfigElement)
        End Get
        Set(ByVal value As UrlConfigElement)
            If Not (BaseGet(index) Is Nothing) Then
            End If
            BaseAdd(index, value)
        End Set
    End Property
    Default Public Shadows ReadOnly Property Item( _
    ByVal Name As String) As UrlConfigElement
            Return CType(BaseGet(Name), UrlConfigElement)
        End Get
    End Property
    Public Function IndexOf(ByVal url _
    As UrlConfigElement) As Integer
        Return BaseIndexOf(url)
    End Function 'IndexOf
   Public Sub Add(url As UrlConfigElement)
   End Sub 'Add
    Protected Overrides Sub BaseAdd(ByVal element _
    As ConfigurationElement)
        BaseAdd(element, False)
    End Sub 'BaseAdd
    Public Overloads Sub Remove(ByVal url _
    As UrlConfigElement)
        If BaseIndexOf(url) >= 0 Then
        End If
    End Sub 'Remove
   Public Sub RemoveAt(index As Integer)
   End Sub 'RemoveAt
   Overloads Public Sub Remove(name As String)
   End Sub 'Remove
   Public Sub Clear()
   End Sub 'Clear
End Class 'UrlsCollection 

' Define the UrlConfigElement for the 
' types contained by the UrlsSection.
Public Class UrlConfigElement
   Inherits ConfigurationElement
   Public Sub New(name As String, url As String)
      Me.Name = name
      Me.Url = url
   End Sub 'New
   Public Sub New()
    End Sub
    <ConfigurationProperty("name", _
    DefaultValue:="Microsoft", _
    IsRequired:=True, _
    IsKey:=True)> _
    Public Property Name() As String
            Return CStr(Me("name"))
        End Get
        Set(ByVal value As String)
            Me("name") = Value
        End Set
    End Property
    <ConfigurationProperty("url", _
    DefaultValue:="", _
    IsRequired:=True), _
    RegexStringValidator("\w+:\/\/[\w.]+\S*")> _
    Public Property Url() As String
            Return CStr(Me("url"))
        End Get
        Set(ByVal value As String)
            Me("url") = Value
        End Set
    End Property
    <ConfigurationProperty("port", _
    DefaultValue:=0, IsRequired:=False), _
    IntegerValidator(MinValue:=0, _
    MaxValue:=8080, ExcludeRange:=False)> _
   Public Property Port() As Integer
            Return CInt(Me("port"))
        End Get
        Set(ByVal value As Integer)
            Me("port") = value
        End Set
    End Property

Class TestingConfigurationCollectionAttribute
   Shared Sub ShowUrls()
            Dim myUrlsSection As UrlsSection = _
            If myUrlsSection Is Nothing Then
                Console.WriteLine("Failed to load UrlsSection.")
                Console.WriteLine("My URLs:")
                Dim i As Integer
                For i = 0 To myUrlsSection.Urls.Count - 1
                    Console.WriteLine("  #{0 {1: {2", i, _
                    myUrlsSection.Urls(i).Name, _
                    myUrlsSection.Urls(i).Url + " port " + _
                Next i
            End If
      Catch e As Exception
      End Try
   End Sub 'ShowUrls
   ' Create the custom section.
   ' It will contain a nested section as 
   ' defined by the UrlsSection (<urls>...</urls>).
   Shared Sub CreateSection(sectionName As String)
      ' Get the current configuration (file).
        Dim config As System.Configuration.Configuration = _
        ConfigurationManager.OpenExeConfiguration( _
      Dim urlsSection As UrlsSection
      ' Create an entry in the <configSections>. 
      If config.Sections(sectionName) Is Nothing Then
         urlsSection = New UrlsSection()
         config.Sections.Add(sectionName, urlsSection)
      End If
      ' Create the actual target section and write it to 
      ' the configuration file.
        If config.Sections(("/configuration/" + sectionName)) _
        Is Nothing Then
            urlsSection = config.GetSection(sectionName) '
             urlsSection.SectionInformation.ForceSave = True
        End If
   End Sub 'CreateSection
    Public Overloads Shared Sub Main(ByVal args() As String)
        Console.WriteLine("[Current URLs]")
    End Sub 'Main

End Class 'TestingConfigurationCollectionAttribute

The following is an excerpt of the configuration file containing the custom section as defined in the previous sample.

    <section name="MyUrls" 
      ConfigurationCollectionAttribute, Version=, 
      Culture=neutral, PublicKeyToken=null" />
      <clear />
      <add name="Microsoft" url="" port="0" />


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

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

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

.NET Framework

Supported in: 2.0

Community Additions