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:

publicsealedclassExecutionModuleCollection : NameObjectCollectionBase

{

privatereadonlyobject syncRoot = newobject();

publicobject SyncRoot

{

get { returnthis.syncRoot; }

}

publicstring[] AllKeys {

get

{

returnthis.BaseGetAllKeys();

}

}

publicIExecutionModulethis[int index]

{

get

{

return (IExecutionModule) this.BaseGet(index);

}

internalset

{

this.BaseSet(index, value);

}

}

publicIExecutionModulethis[string name] {

get

{

return (IExecutionModule) base.BaseGet(name);

}

internalset

{

base.BaseSet(name, value);

}

}

publicvoid CopyTo(Array dest, int index)

{

Array.Copy(base.BaseGetAllValues(), dest, index);

}

publicIExecutionModule Get(string name)

{

return (IExecutionModule)base.BaseGet(name);

}

publicstring GetKey(int index)

{

returnthis.Keys[index].ToString() ;

}

publicvoid 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.