NameObjectCollectionBase Sample c#


this is a  special collection in  System.Collections.Specialized . Main speaciality that it allows duplication keys to be added to the hashtable. It provides the abstract base class for a collection of associated String keys and Object values that can be accessed either with the key or with the index.

An Example:

 public sealed class ExecutionModuleCollection : NameObjectCollectionBase
    {
        private readonly object syncRoot = new object();
 
        public object SyncRoot
        {
            get { return this.syncRoot; }
        }
 
        public string[] AllKeys {
            get
            {
                return this.BaseGetAllKeys();
            }
        }
 
 
        public IExecutionModule this[int index]
        {
            get
            {
                return (IExecutionModule) this.BaseGet(index);
            }
            internal set
            {
                this.BaseSet(index, value);
            }
        }
 
        public IExecutionModule this[string name] {
            get
            {
                return (IExecutionModule) base.BaseGet(name);      
            }
            internal set
            {
                base.BaseSet(name, value);
            }
        }
 
 
        public void CopyTo(Array dest, int index)
        {
            Array.Copy(base.BaseGetAllValues(), dest, index);
        }
 
        public IExecutionModule Get(string name)
        {
            return (IExecutionModule)base.BaseGet(name);
        }
 
        public string GetKey(int index)
        {
            return  this.Keys[index].ToString() ;
        }
 
        public void Add(ExecutionModule module)
        {
            base.BaseAdd(module.Name, module);
        }
    }

Attention:

You can not insert value in specific order because it uses a hashtable in background and this kind of insertation break it.If you need it to be ordered, you should  use  an OrderedDictionary or SortedDictionary<T,T>.

About Thread Safety

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

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.

Advertisement

About bpostaci
Escalation Engineer in Microsoft.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: