Click to See Complete Forum and Search --> : new to c#, struggling to manage Dictionarys


andycoates
June 24th, 2008, 07:59 AM
Hey,

I'm fairly new to C# (and to OOP in general) and whilst I have the nasty habit of learning by example I'm still enjoying the language a *lot* coming from a Perl/C background.

My problem is I'm struggling to find an equivalent way of implementing hashes of objects like Perl/PHP does, specifically in managing the hash/dictionary.

Hashtable myTable = new Hashtable();
myTable["key"] = value;

I'm okay with that until the value being stored is a class, and being new to OOP and classes I'm not sure I'm doing this right.

In Perl or PHP I'd do sometimes do things like:

$variable[key]["field1"] = $foo;
$variable[key]["field2"] = $bar;

In C# I'm creating a class that has those field properties, creating a new instance of that class, and then adding it to the Hashtable, e.g.

MyClass myClass = new MyClass();
myClass.field1 = foo;
myClass.field2 = bar;
myTable.Add(key,myClass);

So for so good for me, and it seems simple enough. My hurdle is the next step where I might want to update one of the class properties. Like in Perl/PHP I'd do do:

$variable[key]["field1"] = $newValue;

What would I do in C#? In my mind I'd do:

myTable[key].field1 = newValue;

That doesn't work though, so I presume thats not the right way of doing things. So my next step was to write a class to manage handling the Hashtable. Doing that I could write a function to return a MyClass object based on the key, e.g.

managerClass.find(key).field1= newValue;

That works like a charm, but:

a) again, is it the right way to do it?
b) if the find function can't find the key it returns null and I get null exception errors. I could write a Contains() to check if its got the key, but it feels like i'd be doing 2 lookups per property update (as the entry is found by my find() function).

Perhaps I still need to get my head around classes and OOP a little more and Perl/PHP has made me lazy :) but any pointers in the right direction would be appreciated.

Thanks in advance.
Andy.

TheCPUWizard
June 24th, 2008, 09:06 AM
1) Welcome to CG.
2) Please use code tags when posting
3) A Dictionary<T,V> is what you want
4) Look at "bool TryGetValue(T key, out V value)"
5) Please use code tags when posting
6) Welcome to CG.
7) Please review items #2 and #5.

andycoates
June 24th, 2008, 10:13 AM
Hey,

Thanks for the reply, and apologies for the code tags.

Changed my Hashtable to Dictionary and specified the key/value types and it seems to work nicely, especially for adding entries. The TryGetValue also very handy for checking a key exists and fetching the value to update!

Thanks!