I am trying to implement a string indexer for a C# class, but when you set a property the dictionary gets set and not the property. It is probably something simple that i am missing, i just can’t see it.
objFiveProp temp = new objFiveProp();
temp["index1"] = 3;
sets the temp._items[“index1”].value to 3.
Class:
public class objFiveProp
{
#region Properties
private Dictionary<string, int> _items;
public int this[string key]
{
get { return _items[key]; }
set { _items[key] = value; }
}
public int index1 { get; set; }
public int index2 { get; set; }
public int index3 { get; set; }
public int index4 { get; set; }
public int index5 { get; set; }
#endregion
#region Constructor
public objFiveProp()
{
index1 = 0;
index2 = 0;
index3 = 0;
index4 = 0;
index5 = 0;
_items = new Dictionary<string, int>();
_items.Add("index1", index1);
_items.Add("index2", index2);
_items.Add("index3", index3);
_items.Add("index4", index4);
_items.Add("index5", index5);
}
#endregion
}
That’s how it works. The Dictionary contains a copy of the integers you use to set it up – not a reference to the properties.
I would tackle this by using something like:
This causes your properties to always pull the values stored in your dictionary, as well as save there, so there aren’t two copies of the values.