Would you consider adding a method to RTL’s Dictionary class to try to retrieve a value with a given key without raising an exception. I would propose .NET’s TryGetValue() method:
bool Dictionary<T, U>.TryGetValue(TKey key, out TValue value)
It looks like this method was present in the deprecated Sugar library but hasn’t made it over to RTL.
An alternative to this method would be a Lookup() method that returns a default value if the key isn’t present in the Dictionary. Something like:
Normal lookup already does not raise an exception, it returns nil for unknown keys.
(Sugar used . NET’s model, of raising exceptions for unknown keys, while RTL2 adopted Cocoa’s model, which I personally much prefer (and also because porting Fire from pure Cocoa to RTL2 was a large driving factor for RTL2 ;).
I suppose the downside of not having a lookup method is that for every key check that is valid you have to do a check to get the value:
Dictionary<string, string> contacts = new Dictionary<string, string> {
{"Peter", "Parker"},
{"Tony", "Stark"}
};
string s = contacts.GetItem(“Garry”);
if (s == null) {
s = “some default value”;
} else {
// Do something with s
}
Compare this to a fictional lookup method:
string s = contacts.GetItemWithDefault(“Garry”, “Default Surname”);
// Use s
It’s an Elements System Function available to all languages; System Functions lists them all.
C# iirc also has an operator for this but I forget/ think it’s “??”, as in
string s = contacts[“Garry”] ?? “Default Surname”;
but (a) I could be wrong as (b) I never used it and I find its less readable. there’s also inline if:
string s = if( x > 5, contacts[“Garry”], contacts[“marc”]);
which is special ij that it assures only one of the two parameters will get called/evaluated (opposed to a custom function called if that would invoke both before the method call), which is important of the two values have side effects or are costly.