Thursday, January 8, 2009

A generic ConfigurationElementCollection implementation

Some quick untested and uncompiled code that I modified from Microsoft, which wanted to save for later reference:

ConfigurationElementCollection class:



public class ConfigurationElementCollection<element_type>
: ConfigurationElementCollection
where ELEMENT_TYPE : ConfigurationElement, IUniqueConfigurationElement
{

public ConfigurationElementCollection()
{
}

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

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

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

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

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

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

public void Add(ELEMENT_TYPE url)
{
BaseAdd(url);
}

protected override void BaseAdd(ConfigurationElement element)
{
BaseAdd(element, false);
}

public void Remove(ELEMENT_TYPE 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();
}

}



IUniqueConfigurationElement interface:



public interface IUniqueConfigurationElement
{
string Name { get; }
}

1 comment:

Bronumski said...

I ended up doing something similar however when I ran my tests I found that the Remove method didn't work as I expected. You don't want to pass the reference of the object you want to remove to the BaseRemove method you need to pass the key.

So instead of:
I ended up doing something similar however when I ran my tests I found that the Remove method didn't work as I expected. You don't want to pass the reference of the object you want to remove to the BaseRemove method you need to pass the key.

So instead of:
BaseRemove(configurationElement);

Use:
BaseRemove(GetElementKey(configurationElement));

Also my class implements IList<T> which defines all the methods you need to implement.

There was an error in this gadget