.NET Framework Class Library
ConfigurationCollectionAttribute Class

Updated: November 2007

Declaratively instructs the .NET Framework to create an instance of a configuration element collection. This class cannot be inherited.

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

Visual Basic (Declaration)
<AttributeUsageAttribute(AttributeTargets.Class Or AttributeTargets.Property)> _
Public NotInheritable Class ConfigurationCollectionAttribute _
    Inherits Attribute
Visual Basic (Usage)
Dim instance As ConfigurationCollectionAttribute
C#
[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Property)]
public sealed class ConfigurationCollectionAttribute : Attribute
Visual C++
[AttributeUsageAttribute(AttributeTargets::Class|AttributeTargets::Property)]
public ref class ConfigurationCollectionAttribute sealed : public Attribute
J#
/** @attribute AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Property) */
public final class ConfigurationCollectionAttribute extends Attribute
JScript
public final class ConfigurationCollectionAttribute extends Attribute

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

Note:

The simplest way to create 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 that contains a collection of elements. The other 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 that contains custom elements of type UrlConfigElement. The example code writes the custom configuration section to the application configuration file. The key for this example is the Urls property, decorated with the ConfigurationCollectionAttribute.

Visual Basic
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
        Get
            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)
      Add(url)
   End Sub 'New


    Public Overrides ReadOnly Property CollectionType() _
    As ConfigurationElementCollectionType
        Get
            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
        Get
            Return CType(BaseGet(index), UrlConfigElement)
        End Get
        Set(ByVal value As UrlConfigElement)
            If Not (BaseGet(index) Is Nothing) Then
                BaseRemoveAt(index)
            End If
            BaseAdd(index, value)
        End Set
    End Property

    Default Public Shadows ReadOnly Property Item( _
    ByVal Name As String) As UrlConfigElement
        Get
            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)
      BaseAdd(url)
   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
            BaseRemove(url.Name)
        End If
    End Sub 'Remove
   Public Sub RemoveAt(index As Integer)
      BaseRemoveAt(index)
   End Sub 'RemoveAt

   Overloads Public Sub Remove(name As String)
      BaseRemove(name)
   End Sub 'Remove

   Public Sub Clear()
      BaseClear()
   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
        Get
            Return CStr(Me("name"))
        End Get
        Set(ByVal value As String)
            Me("name") = Value
        End Set
    End Property

    <ConfigurationProperty("url", _
    DefaultValue:="http://www.microsoft.com", _
    IsRequired:=True), _
    RegexStringValidator("\w+:\/\/[\w.]+\S*")> _
    Public Property Url() As String
        Get
            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
        Get
            Return CInt(Me("port"))
        End Get
        Set(ByVal value As Integer)
            Me("port") = value
        End Set
    End Property
End Class 'UrlConfigElement 


Class TestingConfigurationCollectionAttribute

   Shared Sub ShowUrls()

      Try
            Dim myUrlsSection As UrlsSection = _
            ConfigurationManager.GetSection("MyUrls")

            If myUrlsSection Is Nothing Then
                Console.WriteLine("Failed to load UrlsSection.")
            Else
                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 " + _
                    myUrlsSection.Urls(i).Port.ToString())
                Next i
            End If
      Catch e As Exception
         Console.WriteLine(e.ToString())
      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 associated
      ' with the application.
      Dim config As System.Configuration.Configuration = _
      ConfigurationManager.OpenExeConfiguration( _
      ConfigurationUserLevel.None)

      Dim urlsSection As UrlsSection

      ' Create a configuration section and save it
      ' to the configuration file. 
      If config.Sections(sectionName) Is Nothing Then
         urlsSection = New UrlsSection()
         config.Sections.Add(sectionName, urlsSection)
         config.Save()
      End If


   End Sub 'CreateSection


    Public Overloads Shared Sub Main(ByVal args() As String)
        Console.WriteLine("[Current URLs]")
        CreateSection("MyUrls")
        ShowUrls()
        Console.ReadLine()
    End Sub 'Main

End Class 'TestingConfigurationCollectionAttribute

C#
using System;
using System.Configuration;


namespace Samples.AspNet
{


    // 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 : ConfigurationSection
    {
        // Declare the collection element.
        UrlConfigElement url;

        public UrlsSection()
        {
            // 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();
        }


        // 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(typeof(UrlsCollection), 
            AddItemName="addUrl", 
            ClearItemsName="clearUrls",
            RemoveItemName="RemoveUrl")]
        public UrlsCollection Urls
        {

            get
            {
                UrlsCollection urlsCollection = 
                (UrlsCollection)base["urls"];
                return urlsCollection;
            }
        }



    }

    // Define the UrlsCollection that will contain the UrlsConfigElement
    // elements.
    public class UrlsCollection : ConfigurationElementCollection
    {
        public UrlsCollection()
        {
            UrlConfigElement url = (UrlConfigElement)CreateNewElement();
            Add(url);
        }

        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.AddRemoveClearMap;
            }
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new UrlConfigElement();
        }

        protected override Object GetElementKey(ConfigurationElement element)
        {
            return ((UrlConfigElement)element).Name;
        }

        public UrlConfigElement this[int index]
        {
            get
            {
                return (UrlConfigElement)BaseGet(index);
            }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }

        new public UrlConfigElement this[string Name]
        {
            get
            {
                return (UrlConfigElement)BaseGet(Name);
            }
        }

        public int IndexOf(UrlConfigElement url)
        {
            return BaseIndexOf(url);
        }

        public void Add(UrlConfigElement url)
        {
            BaseAdd(url);
        }
        protected override void BaseAdd(ConfigurationElement element)
        {
            BaseAdd(element, false);
        }

        public void Remove(UrlConfigElement url)
        {
            if (BaseIndexOf(url) >= 0)
                BaseRemove(url.Name);
        }

        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }

        public void Remove(string name)
        {
            BaseRemove(name);
        }

        public void Clear()
        {
            BaseClear();
        }
    }

    // Define the UrlConfigElement for the types contained by the 
    // UrlsSection.
    public class UrlConfigElement : ConfigurationElement
    {
        public UrlConfigElement(String name, String url)
        {
            this.Name = name;
            this.Url = url;
        }

        public UrlConfigElement()
        {
            // Initialize as follows, if no attributed 
            // values are provided.
            // this.Name = "Microsoft";
            // this.Url = "http://www.microsoft.com";
            // this.Port = 0;
        }

        [ConfigurationProperty("name", DefaultValue = "Microsoft",
            IsRequired = true, IsKey = true)]
        public string Name
        {
            get
            {
                return (string)this["name"];
            }
            set
            {
                this["name"] = value;
            }
        }

        [ConfigurationProperty("url", DefaultValue = "http://www.microsoft.com",
            IsRequired = true)]
        [RegexStringValidator(@"\w+:\/\/[\w.]+\S*")]
        public string Url
        {
            get
            {
                return (string)this["url"];
            }
            set
            {
                this["url"] = value;
            }
        }

        [ConfigurationProperty("port", DefaultValue = (int)0, IsRequired = false)]
        [IntegerValidator(MinValue = 0, MaxValue = 8080, ExcludeRange = false)]
        public int Port
        {
            get
            {
                return (int)this["port"];
            }
            set
            {
                this["port"] = value;
            }
        }
    }


    class TestingConfigurationCollectionAttribute
    {
        static void ShowUrls()
        {

            try
            {
                UrlsSection myUrlsSection =
                   ConfigurationManager.GetSection("MyUrls") as UrlsSection;

                if (myUrlsSection == null)
                    Console.WriteLine("Failed to load UrlsSection.");
                else
                {
                    Console.WriteLine("My URLs:");
                    for (int i = 0; i < myUrlsSection.Urls.Count; i++)
                    {
                        Console.WriteLine("  #{0} {1}: {2}", i,
                            myUrlsSection.Urls[i].Name,
                            myUrlsSection.Urls[i].Url + " port " +
                            myUrlsSection.Urls[i].Port);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        // Create a custom section.
        // It will contain a nested section as 
        // defined by the UrlsSection (<urls>...</urls>).
        static void CreateSection(string sectionName)
        {
            // Get the current configuration file associated
            // with the application.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            UrlsSection urlsSection;

            // Create a configuration section and save it
            // to the configuration file.
            if (config.Sections[sectionName] == null)
            {
                urlsSection = new UrlsSection();
                config.Sections.Add(sectionName, urlsSection);
                config.Save();
            }


        }


        static void Main(string[] args)
        {   
            Console.WriteLine("[Current URLs]");
            CreateSection("MyUrls");
            ShowUrls();
            Console.ReadLine();
        }
    }
}

System..::.Object
  System..::.Attribute
    System.Configuration..::.ConfigurationCollectionAttribute
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 Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

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

.NET Framework

Supported in: 3.5, 3.0, 2.0
Page view tracker