You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Pay attention to the bang (!) operator used in the first method.
API Proposal
Now Imagine we could apply the attribute to the second method:
[return:MaybeNullIfNull(nameof(defultValue)]publicstaticTValueGetValueOrDefault<TKey,TValue>(thisIReadOnlyDictionary<TKey,TValue>dictionary,TKeykey,TValue?defaultValue)// defaultValue is nullable now.{if(dictionaryisnull){ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);}returndictionary.TryGetValue(key,outTValue?value)?value:defaultValue;}
In this case bang operator won't be required, and compiler can infer nullability of returned value both based on the type of the dictionary and the default value.
API Usage
vardict1=newDictionary<int,string>();stringstr1=dict1.GetValueOrDefault(1,null);// compiler emits warning/error because method can return null;stringstr2=dict1.GetValueOrDefault(1,"abc");// compiler is happy.vardict2=newDictionary<int,string?>();stringstr3=dict2.GetValueOrDefault(1,"abc");// compiler complains.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
Background and motivation
Sometimes several parameters of the same type affect the nullability of result value.
For example, here are the methods from CollectionExtensions:
Pay attention to the bang (!) operator used in the first method.
API Proposal
Now Imagine we could apply the attribute to the second method:
In this case bang operator won't be required, and compiler can infer nullability of returned value both based on the type of the dictionary and the default value.
API Usage
Beta Was this translation helpful? Give feedback.
All reactions