Alejandro Guillen
Alejandro Guillen

Reputation: 41

dictionary trygetvalue null

 private Dictionary<Type, Bag<Event>> events = new Dictionary<Type, Bag<Event>>();

 internal Bag<T> GetEventList<T>() where T:class
 {
    Type type = typeof(T);
    Bag<Event> b;
    if (events.TryGetValue(type, out b))
    {
        return b as Bag<T>;
    }
    else {
        b = new Bag<T>() as Bag<Event>;
        events[type] = b;
        return b as Bag<T>;
    }
}

internal void AddEvent<T>(T ev) where T:class,Event
{
    Type type = typeof(T);
    Bag<Event> b;
    if (events.TryGetValue(type, out b))
    {
        b.Add(ev); // <= NullReferenceException, b is null
    }
    else {
        b = new Bag<T>() as Bag<Event>;
        events.Add(type, b);
        b.Add(ev);
    }
}

I always get a NullReferenceException inside AddEvent. The events Dictionary is used only in those two functions, I have no idea why the value is null... I'm not inserting null values anywhere!

I'm going nuts here...

Upvotes: 2

Views: 2994

Answers (3)

dlev
dlev

Reputation: 48596

The likely culprit is this line:

b = new Bag<T>() as Bag<Event>;

The as cast is probably failing, which will assign null to b.

My guess would be that you are using a subclass of Event as the type of T, and since Bag<T> is not covariant on the type parameter (I assume it's a class, so it can't be,) the cast fails, and you end up with b being null.

Update: Based on the comment below, the issue is indeed the as cast. To fix things up, just create a new Bag<Event>(), no cast required.

Upvotes: 4

burning_LEGION
burning_LEGION

Reputation: 13450

NullReferenceException is thrown when Bag<T> can not cast to Bag<Event>

if you change signature to internal void AddEvent<T>(Event ev) where T : class exception will dismiss

Upvotes: 0

MgSam
MgSam

Reputation: 12803

Somewhere a null is being associated with the key type.

Step through the code in the debugger and check the state of the dictionary before the NullReferenceException is thrown.

Upvotes: 0

Related Questions