proper use of a TKey in a Dictionary  
Author Message
Sweeps78





PostPosted: Visual C# General, proper use of a TKey in a Dictionary Top

We have a system that the core of it was developed using the Generic:

Dictionary<TKey, TValue>

At the top of our library we have a base abstract class, we'll call ParentClass. In ParentClass, there is a Name property. Inside the ParentClass is also the Dictionary:

Dictionary<string, ParentClass> dict = new Dictionary<string, ParentClass>;

The Dictionary is private, and we have our own Add method that goes into the Dictionary and adds the new object as the value, and uses the name as the Key:

dict.Add(obj.Name, obj);

obj being an object of a class derived from ParentClass.

My question is this. Is it common practice to use something like a name as a key value I guess my confusion lies in thinking of a key as the same thing as a primary key in a database, which in most all cases you would never use a name as a primary key. However, we want all of the names to be unique in our system. In a database, the primary key really should never change, however, in our system the names must be able to change, which when using Dictionaries, sure the name of the Value (ParentClass object) itself can change, but the associated Key (which is the name of that ParentClass object) of that particular item will not be changed, which creates a problem.

That said, I do not want to double post because my topic here is getting too closely related to my other thread:

http://www.hide-link.com/ ;SiteID=1

Please somebody help clear up my confusion





Visual C#20  
 
 
Thilak Nathen





PostPosted: Visual C# General, proper use of a TKey in a Dictionary Top

I don't see why dict.Add(obj.Name, obj) would be wrong As long as name is unique, it's perfectly valid.

And I've never seen a rule (or best practise) anywhere that says the key of a dictionary has to be a database primary key. It's just a data structure... which may or may not contain database related objects.


 
 
Sweeps78





PostPosted: Visual C# General, proper use of a TKey in a Dictionary Top

I never said that it has to be a primary key. In fact my project has nothing to do with a database. I was merely using primary key as an example for where my confusion lies.


 
 
Matthew Watson





PostPosted: Visual C# General, proper use of a TKey in a Dictionary Top

In answer to your question: Yes, it is common practice. Go right ahead. :)

 
 
Sweeps78





PostPosted: Visual C# General, proper use of a TKey in a Dictionary Top

Thanks:)

Since I have to be able to change my dictionary keys, is it more appropriate to develop my own collection inheriting from:

System.Collections.ObjectModel.KeyedCollection<TKey, TItem>

Or is there a better way