❔ ?[] operator for dictionaries
Is not working. It is explained here. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-
Can somebody help?
Member access and null-conditional operators and expressions:
C# operators that you use to access type members or null-conditionally access type members. These operators include the dot operator -
.
, indexers - [
, ]
, ^
and ..
, and invocation - (
, )
.22 Replies
it is working exactly as it should
your exception is because the key is not present in the dictionary, not because the dictionary is null
you should use something like
TryGetValue
instead of the indexer if you aren't sure the key existsI am not testing against if dictionary is null
you are with
_data?["humidity"]
_data?
tests if _data
is null before trying to use the indexer
it has nothing to do with finding keys in the dictionaryOkay I see, how to yield null in this situation? Does csharp has such operator?
i don't know what you mean by that
the pattern to do this would be something like
You can just do
data.TryGetValue("humidity", out var val) ? val : default
No,
TryGetValue
returns a boolYes
But what if dictionary is null
Then its nullable bool
Isn't it?
I don't think they want to test for whether dict is null
Correct
Oh I guess I was wrong
My bad
I mean data can be null, so its nullable bool
using
??
to short-circuit
although this is less readable than I anticipatedYeah, I just thought you wanted to check for existance of a value in a dictionary 😅
You can make it an extension method
You could make an extension method like, GetOrDefault
MS should do that :
Actually
CollectionExtensions.GetValueOrDefault Method (System.Collections.G...
Tries to get the value associated with the specified key in the dictionary.
Turns out it's already there
Guh
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.