Reputation: 39437
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
Upvotes: 0
Views: 253
Reputation: 545588
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)
Upvotes: 0
Reputation: 9965
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.
Upvotes: 2