I have a static dictionary that is being used like a little "cache".
In some place, I create a new object and set some property of it to have a value from the dictionary.
Later, for some reasons I am encoding some string properties of the object using PropertyInfo.SetValue.
The issue is - the dictionary value is also changed.
I tried to "copy" the string before encoding it, but seems the issue is the setValue and not the string changing.
Person p = new Person();
//Cache.Countries is a static dictionary of countries
//each Country contains a few properties, not just description
p.Country = Cache.Countries[1];
encodeObj(p.Country);
The encodeObj funtion runs foreach on all object properties, which encodes all the strings on a given object.
private void encodeObj(object obj)
{
foreach(var pi in obj.GetType().GetProperties())
{
object propValue = pi.GetValue(obj,null);
if(pi.PropertyType == typeof(string) && !string,IsNullOrEmpty((string)propValue))
{
//the Copy is what I tried but didn't work
string temp = string.Copy((string)propValue);
string encoded = WebUtility.HtmlEncode(temp);
//here is the problematic line
//if I watch now Cache.Countries[1].<the current property info>
//it is ok
pi.SetValue(obj,encoded)
//here if I watch again Cache.Countries[1].<the current property info>
//it was changed to the encoded value!
}
}
}
How can I SetValue without changing the source dictionary?