I am trying to make a simple parser where I have key, value pairs that I would like to assign to variables. I want to map a String to a variable. I think the below test class should express what I would like to do. But how can I store a variable so I can update it?
[TestClass]
public class StringObjectMapperTest
{
[TestMethod]
public void TestMethod1()
{
string string1 = "";
string string2 = "";
StringObjectMapper mapper = new StringObjectMapper();
mapper.Add("STRING1", ref string1);
mapper.Add("STRING2", ref string2);
mapper.Set("STRING1", "text1");
Assert.AreEqual("text1", string1); // FAILS as string1 is still ""
}
}
public class StringObjectMapper
{
private Dictionary<string, string> mapping = new Dictionary<string, string>();
public StringObjectMapper()
{
}
public void Set(string key, string value)
{
string obj = mapping[key];
obj = value;
}
internal void Add(string p, ref string string1)
{
mapping.Add(p, string1);
}
}
Update: I am trying to use a Boxed String but this also seems to act like a immutable object, any idea why?
[TestClass]
public class StringObjectMapperTest
{
[TestMethod]
public void TestMethod1()
{
BoxedString string1 = "string1";
BoxedString string2 = "string2";
StringObjectMapper mapper = new StringObjectMapper();
mapper.Add("STRING1", ref string1);
mapper.Add("STRING2", ref string2);
mapper.Set("STRING1", "text1");
string s = string1;
Assert.AreEqual("text1", s); // Fails as s = "string1" ???
}
}
public struct BoxedString
{
private string _value;
public BoxedString(string value)
{
_value = value;
}
public void Set(string value)
{
_value = value;
}
static public implicit operator BoxedString(string value)
{
return new BoxedString(value);
}
static public implicit operator string(BoxedString boxedString)
{
return boxedString._value;
}
}
public class StringObjectMapper
{
private Dictionary<string, BoxedString> mapping = new Dictionary<string, BoxedString>();
public StringObjectMapper()
{
}
public void Set(string key, string value)
{
BoxedString obj = mapping[key];
obj.Set(value);
}
internal void Add(string p, ref BoxedString obj)
{
mapping.Add(p, obj);
}
}
structBoxedString to publicclassBoxedString, it will work. don't forget to green check the answer that you think is best