1+ using System . Collections . Generic ;
2+
3+ namespace Patterns . Collections
4+ {
5+ /// <summary>
6+ /// Defines a default implementation of the <see cref="IDictionaryValueRetriever{TKey,TValue}" /> interface.
7+ /// </summary>
8+ /// <typeparam name="TKey">The type of the key.</typeparam>
9+ /// <typeparam name="TValue">The type of the value.</typeparam>
10+ public class DictionaryValueRetriever < TKey , TValue > : IDictionaryValueRetriever < TKey , TValue >
11+ {
12+ private readonly IDictionary < TKey , TValue > _dictionary ;
13+ private readonly bool _throwKeyNotFoundExceptions ;
14+
15+ /// <summary>
16+ /// Initializes a new instance of the <see cref="DictionaryValueRetriever{TKey, TValue}" /> class.
17+ /// </summary>
18+ /// <param name="dictionary">The dictionary.</param>
19+ /// <param name="throwKeyNotFoundExceptions">
20+ /// if set to <c>true</c>, throw KeyNotFoundExceptions for missing keys.
21+ /// </param>
22+ public DictionaryValueRetriever ( IDictionary < TKey , TValue > dictionary , bool throwKeyNotFoundExceptions )
23+ {
24+ _dictionary = dictionary ;
25+ _throwKeyNotFoundExceptions = throwKeyNotFoundExceptions ;
26+ }
27+
28+ /// <summary>
29+ /// Retrieves the value at the specified key.
30+ /// </summary>
31+ /// <param name="key">The key.</param>
32+ /// <returns></returns>
33+ /// <exception cref="System.NotImplementedException"></exception>
34+ public TValue Retrieve ( TKey key )
35+ {
36+ if ( ! _dictionary . ContainsKey ( key ) )
37+ {
38+ if ( _throwKeyNotFoundExceptions ) throw new KeyNotFoundException ( ) ;
39+
40+ return default ( TValue ) ;
41+ }
42+
43+ return _dictionary [ key ] ;
44+ }
45+ }
46+ }
0 commit comments