Task: Review generic dictionary value retrieval to ensure that `TryGetValue()` is used instead of `dic[key]`
- Dominant language
- C#
- Stars
- 2.4k
- Forks
- 658
- Avg merge
- 3d 5h
- Merged PRs (30d)
- 9
Description
### 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` 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[field.Number];
if (instance == null)
{
instance = LoadNumeric(field);
numericInstances[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` 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`, we don't need to make these changes. These are rare, though.
Contributor guide
Assessment
This issue has not been assessed yet.