Let’s say I have the following class:
public class MyClass {
public string FirstAttribute {
get {
return Attributes["FirstAttribute"];
}
set {
Attributes["FirstAttribute"] = value;
}
}
public string SecondAttribute {
get {
return Attributes["SecondAttribute"];
}
set {
Attributes["SecondAttribute"] = value;
}
}
public Dictionary<string, string> Attributes;
public MyClass(Dictionary<string,string> att) {
Attributes = att;
}
}
and I wanted to be able to obtain a pointer to the value that is stored in the Dictionary, so that I can get and set the values (yes unsafe) directly without having to wait for the Dictionary to search for the element by key every time.
Is there a way to do that in c#?
No, I don’t believe so. You could store a mutable wrapper in the dictionary though:
Then create the dictionary (which should be private, by the way – public fields are a really bad idea other than for constants) as a
Dictionary<string, Wrapper<string>>. You can then keep fields for theWrapper<string>objects associated with"FirstAttribute"and"SecondAttribute".Frankly I don’t think this would be a particularly good idea – I’d just stick with the dictionary lookup – but it’s an option. (Assuming nothing’s going to change which wrapper is associated with the keys.)
Another option is simply to use fields for the two specific attributes – when you’re asked to set a new value, set it in the dictionary and set a field. When you’re asked for the current value, just return the value from the field. Of course, that’s assuming that you’re in control of the dictionary (i.e. so it can’t change outside your class).