views:

79

answers:

2

I have some code that adds a Func<short> to a Dictionary<byte, Func<short>> at index 0. Later on, some code within the class that contains the dictionary attempts to extract this Func (via TryGetValue) and execute it, throwing an exception if it does not work. Even though the index being accessed is valid, it throws the exception that signifies the function extraction failed. Why is this? (can provide code if necessary)

    //processor construction and setup
    VirtualProcessor processor = new VirtualProcessor();
    ...
    processor.InputChannels.Add(0, () => { return 2; });//the func i'm trying to access
    //end processor construction and setup
    //build program
    Dictionary<short, Command> commands = new Dictionary<short, Command>();
    commands.Add(0, CommandFactory.CreateInputCommand(0, 0));//this, in a roundabout way, attempts to call the func
    commands.Add(1, CommandFactory.CreateLoadCommand(1, 200));
    commands.Add(2, CommandFactory.CreateAddCommand(0, 1, 2));
    commands.Add(3, CommandFactory.CreateHaltCommand());
    //end build program
    //execution
    processor.CurrentProgram = commands;
    processor.ExecuteTillHalt();
    //end execution
    Console.ReadLine();

Somewhere in a desert of switch cases, in another class...

    Func<short> inChannel;
    InputChannels.TryGetValue(command.Data2, out inChannel);//the attempt to access the func, this is the second value supplied to CreateInputCommand above
    if (inChannel != null)
            Registers[command.Data1] = inChannel();//should be here
    else
            throw new InvalidInputChannelException("Invalid input channel " + command.Data2); //throws this
+2  A: 

Possibly a bug in your code - why do you use TryGetValue, and then check the value for null? I would rewrite it as :

if (InputChannels.TryGetValue(command.Data2, out inChannel))
    Registers[command.Data1] = inChannel();
else
    throw ...

If one of those functions return null, you would get the result you described.

Yurik
It still fails when moving that into the if statement.
RCIX
A: 

Make sure that your call to CommandFactory.CreateInputCommand never returns null. In particular, your code suggests that it returns null for the following call:

CommandFactory.CreateInputCommand(0, 0)
Konrad Rudolph
I actually figured it out. I forgot i made a call in a property assigner which wiped out all of the settings for the class. I fixed it now!
RCIX