NightOwl888 opened a new issue, #1168:
URL: https://github.com/apache/lucenenet/issues/1168

   ### Is there an existing issue for this?
   
   - [x] I have searched the existing issues
   
   ### Task description
   
   We need to ensure that most of our `Dictionary<TKey, TValue>` usages 
retrieve values using `TryGetValue()` instead of using indexer `var x = 
dictionary[key]`. In Java, collections are designed not to throw exceptions 
when entries don't exist. Since they always use refernece types, a check for 
`null` is all that is required to determine if the key retrieval was successful.
   
   However, generic .NET dictionaries allow the use of value types which may 
not be nullable, which necessitates there be a `TryGetValue()` method to 
determine whether an entry exists for a given key.
   
   ### Examples:
   
   #### Value Types
   
   ```c#
   float boost = m_boosts[m_fields[i]];
   q.Boost = boost;
   ```
   
   Becomes:
   
   ```c#
   if (m_boosts.TryGetValue(m_fields[i], out float boost))
   {
       q.Boost = boost;
   }
   ```
   
   #### Reference Types
   
   ```c#
   NumericDocValues instance = numericInstances.get(field.number);
   if (instance == null) {
       instance = loadNumeric(field);
       numericInstances.put(field.number, instance);
   }
   return instance;
   ```
   
   Becomes:
   
   ```c#
   if (!numericInstances.TryGetValue(field.Number, out NumericDocValues 
instance) || instance is null)
   {
       instance = LoadNumeric(field);
       numericInstances[field.Number] = instance;
   }
   return instance;
   ```
   
   > Note that for refernence types, we can eliminate the extra check for 
`null` if the rest of the class is analyzed to ensure there can never be `null` 
values in the dictionary.
   
   We used a "squeaky wheel gets the grease" approach when fixing access to 
`Dictionary<TKey, TValue>` calls. So, any gaps that the Lucene tests do not 
cover have probably not yet been addressed.
   
   > NOTE: .NET Generic dictionaries also implement non-generic interfaces. 
When using these non-generic interfaces, the old "check for null" behavior is 
still valid. So, in APIs where we are using `IDictionary` instead of 
`IDictionary<TKey, TValue>`, we don't need to make these changes. These are 
rare, though.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to