I am writing a custom dictionary class for my task but it is giving error. What is the problem at this class ? Thank you
public struct MyValue
{
public int irValue1;
public int irValue2;
}
public class csCustomDictionary : Dictionary<string, MyValue>
{
public void Add(string srKey, int irVal1, int irVal2)
{
if (this.ContainsKey(srKey) == true)
{
this[srKey].irValue1 = this[srKey].irValue1 + irVal1;
this[srKey].irValue1 = this[srKey].irValue2 + irVal2;
}
else
{
MyValue val;
val.irValue1 = irVal1;
val.irValue2 = irVal2;
this.Add(srKey, val);
}
}
}
}
this is the error message

C# 4.0
Is this modified version correct
public class csMyValue
{
public int irValue1;
public int irValue2;
}
public class csCustomDictionary : Dictionary<string, csMyValue>
{
public void Add(string srKey, int irVal1, int irVal2)
{
if (this.ContainsKey(srKey) == true)
{
this[srKey].irValue1 = this[srKey].irValue1 + irVal1;
this[srKey].irValue1 = this[srKey].irValue2 + irVal2;
}
else
{
csMyValue val = new csMyValue();
val.irValue1 = irVal1;
val.irValue2 = irVal2;
this.Add(srKey, val);
}
}
}
The problem is that you’re using a
structas your Value in the Dictionary.When you write:
this[srKey], you actually retrieve a copy of the struct stored as the Dictionary’s value. As such, the.irValue1is trying to set a field on the copy (that will soon disappear).If you change
MyValueto be a class, this should work. This is more appropriate, as well, as you’re making a mutable type, and mutable structs are very rarely a good idea.That being said, you could force this to work via making a temporary, setting the fields, then setting the value in your Dictionary:
If you change
MyValueto be a class instead of a struct, you could write:Since the stored value would be a reference, this will do the change that you wish without requiring lots of dictionary lookups.