craigkeniss...@hotmail.com wrote:
TryGetValue !? What's that ? Why I have to provide an out parameter,
isn't more simple just return the value or null if not found !?
What if "null" is actually the value corresponding to that key?
Example:
Dictionary Dict = new Dictionary();
Dict.Add("key", null);
Now, using your preferred method, the call would be something like:
object value = Dict["key"];
How do you know if it was there or not? In this situation (i.e. the
function -returns- the value), the only way to know is to have the
function (the indexer) throw an exception if it's not found. And in
fact, Dictionary does throw an exception if an entry with the key you
specified is not found. TryGetValue is useful though in a situation
where there is a chance the key might not be there.
object value;
bool Result = Dict.TryGetValue("key", out value);
if (!Result)
{
//The key wasn't in the dictionary.
}
In the first situation, where you use the indexer, it's still possible
to guarantee no exception will be thrown if you use code like this:
if (Dict.ContainsKey("key"))
object value = Dict["key"];
But performance suffers now, because you are doing -two- separate
lookups into the hash table. One for ContainsKey, then doing the exact
same lookup again to fetch it.
I admit, using out parameters feels clunky sometimes and inelegant, but
in this case it is the most elegant and performance efficient way to
handle everything with one function call.