I’ve created this extension method
public static void AddIfNullCreate<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
if (dictionary == null)
{
dictionary = new Dictionary<TKey, TValue>();
}
dictionary.Add(key, value);
}
But when I use it
public void DictionaryTest()
{
IDictionary<int, string> d = GetD();
d.AddIfNullCreate(1,"ss");
}
private IDictionary<int, string> GetD()
{
return null;
}
After calling AddIfNullCreate is d null. Why is that so ?
Just like any other method, a change to the parameter doesn’t change the caller’s argument unless it’s a
refparameter (which it can’t be for an extension method first parameter). The argument is passed by value, even if that value is a reference.One option is to return the dictionary too:
Then:
However, I’m not sure I’d really do that. I think I’d just conditionally create the dictionary in the method itself: