❔ ?[] operator for dictionaries

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
Jimmacle
Jimmacle2y ago
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 exists
.0xdeadc0de
.0xdeadc0deOP2y ago
I am not testing against if dictionary is null
Jimmacle
Jimmacle2y ago
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 dictionary
.0xdeadc0de
.0xdeadc0deOP2y ago
Okay I see, how to yield null in this situation? Does csharp has such operator?
Jimmacle
Jimmacle2y ago
i don't know what you mean by that the pattern to do this would be something like
if(!_data.TryGetValue("humidity", out var value))
value = default;
if(!_data.TryGetValue("humidity", out var value))
value = default;
Kouhai
Kouhai2y ago
You can just do data.TryGetValue("humidity", out var val) ? val : default
.0xdeadc0de
.0xdeadc0deOP2y ago
Console.Write(_data?.TryGetValue("temperature", out string? o) ?? false ? o : default)
Console.Write(_data?.TryGetValue("temperature", out string? o) ?? false ? o : default)
Kouhai
Kouhai2y ago
No, TryGetValue returns a bool
.0xdeadc0de
.0xdeadc0deOP2y ago
Yes
basically, i am little cat
But what if dictionary is null Then its nullable bool Isn't it?
Kouhai
Kouhai2y ago
I don't think they want to test for whether dict is null
.0xdeadc0de
.0xdeadc0deOP2y ago
Correct
Kouhai
Kouhai2y ago
Oh I guess I was wrong My bad
.0xdeadc0de
.0xdeadc0deOP2y ago
I mean data can be null, so its nullable bool using ?? to short-circuit although this is less readable than I anticipated
Kouhai
Kouhai2y ago
Yeah, I just thought you wanted to check for existance of a value in a dictionary 😅 You can make it an extension method Smile
basically, i am little cat
You could make an extension method like, GetOrDefault
.0xdeadc0de
.0xdeadc0deOP2y ago
MS should do that :
Kouhai
Kouhai2y ago
Actually
Kouhai
Kouhai2y ago
Turns out it's already there
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server