I have a class that maintains a static Dictionary
to contain a map between string and another Object (CloudFileClient
in my case). I haven't used static constructor but rather have initialized the variable while declaring.
Problem:
I am facing "Object reference not set to an instance of an object." exception while adding a key to the dictionary. From the stack trace it looks like the Dictionary itself maybe null.
Sample code:
public class Demo
{
// Initalizing the dictionary here.
private static Dictionary<string, CloudFileClient> CloudFileClientReferences = new Dictionary<string, CloudFileClient>();
...
public static Func<string, CloudFileClient> GetCloudFileClient { get; set; } = (string accountName) =>
{
if (!CloudFileClientReferences.ContainsKey(accountName))
{
CloudFileClientReferences[accountName] = CreateCloudFileClient(); // Problem statement.
}
...
}
}
This seems to work fine but occassionaly the app is logging the following error at the "Problem statement" line.
Object reference not set to an instance of an object. at System.Collections.Generic.Dictionary2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) \r\n at System.Collections.Generic.Dictionary2.set_Item(TKey key, TValue value)
What could be the issue here? I have hosted this code within Azure serverless function. I don't think ConcurrentDictionary
would help here as the error would say so. Can a null key cause this? Or should I use static constructor instead?