Dovile Dovile - 23 days ago 5
C# Question

Get hashtable obj by key & change its public properties

First of all I declare a hashtable and its values. The key of a hashtable entry is a GUID and the value is an object with a few string values.

Guid g = Guid.NewGuid();
Hashtable hash = new Hashtable();
InstallationFiles instFiles = new InstallationFiles(string1, string2, string3);
hash.Add(g, instFiles);
//...add many other values with different GUIDs...

My goal is to give a user a possibility to EDIT string 1, string2, string3. To cut a long story short, I am in a position where I can get the "GUID g" of the entry which needs to be edited:

public void edit()
//here I retrieve the GUID g of the item which has to be edited:
object objectHash = item.Tag;
//here i loop through all hash entries to find the editable one:
foreach(DictionaryEntry de in hash)
if(de.Key.ToString() == objectHash)
//here I would like to access the selected entry and change string1 -
//the line below is not working.

hash[de.Key].string1 = "my new value";


How do I make this line work?

hash[de.Key].string1 = "my new value";


Use Dictionary<Guid, InstallationFiles> instead HashTable

upd. You can use this.

 (hash[de.Key] as InstallationFiles).string1 = "asdasd" 

Ok, explanation:

Because Hashtable is not generic type, it contains references on keys and values as Objects.

Thats why, when you access to your value hashtable[mykey], you got reference to Object. To make it as reference to your type (InstallationFiles), you have to from "reference to Object" get "reference to InstallationFiles". Im my sample I use "as" operator to do this.