Home Ask Login Register

Developers Planet

Your answer is one click away!

HaraldDutch February 2016

GetKey in ConfigurationElementCollection from ConfigurationPropertyAttribute?

There are a lot of examples out there that explain how to create your own ConfigurationElementCollection, for instance: Stackoverflow: How to implement your own ConfigurationElementCollection?

One of the functions you'll have to override is GetElementKey:

protected override object GetElementKey(ConfigurationElement element)
  return ((ServiceConfig) element).Port;

where property Port is defined as follows:

[ConfigurationProperty("Port", IsRequired = true, IsKey = true)]
public int Port 
  get { return (int) this["Port"]; }
  set { this["Port"] = value; }

My configuration has several ConfigurationElementCollections that look very similar. The GetElementKey function is the only function that inhibits the use of a generic ConfigurationElementCollection because of the identifier of the key. The ConfigurationPropertyAttribute already informs me which property is the key.

Is it possible to get the Key property via the ConfigurationPropertyAttribute?

Code would be like:

public class ConfigCollection<T> : ConfigurationElementCollection where T: ConfigurationElement, new()
    protected override Object GetElementKey(ConfigurationElement element)
        // get the propertyInfo of property that has IsKey = true
        PropertyInfo keyPropertyInfo = ... 
        object keyValue = keyPropertyInfo.GetValue(element);
        return keyValue;


Mark February 2016

Yes, you can get all the properties of the element and look for the one that has a ConfigurationPropertyAttribute with IsKey == true:

protected override object GetElementKey(ConfigurationElement element)
    object key = element.GetType()
                        .Where(p => p.GetCustomAttributes<ConfigurationPropertyAttribute>()
                                     .Any(a => a.IsKey))
                        .Select(p => p.GetValue(element))

    return key;

Post Status

Asked in February 2016
Viewed 3,564 times
Voted 4
Answered 1 times


Leave an answer

Quote of the day: live life