1

I have a static delegate command. I'm passing a bool to the constructor. However, it is throwing a runtime exception.

public static class myViewModel
{
    public static ICommand myCommand {get; private set;}

    static myViewModel
    {
        //If I change the bool to Object, or to Collection type, no exception assuming that I change myMethod parameter as well to the same type.
        myCommand = new DelegateCommand<bool>(myMethod);
    }

    private static void myMethod (bool myBoolean)
    {
        //To Do
    }
}
nvoigt
  • 75,013
  • 26
  • 93
  • 142
John
  • 101
  • 1
  • 11

1 Answers1

3

Always, always, always tell us what type of exception you got, and what the exception message was. They have many, many different exceptions because every one is thrown for a different reason.

But in this case, it looks like the problem is that bool is a value type, and the code that executes the command is passing it a null for a parameter. But you can't cast null to a value type, and trying to do so will cause a runtime exception:

object o = null;
//  This will compile, but blow up at runtime. 
bool b = (bool)o;
  • 1
    Thank you. You are absolutely right about the `bool?`
    It is no brainer, I should have included the `exception` . Will keep that in mind.
    Thank you
    – John Mar 24 '17 at 13:20
  • are you aware of any issue with the forum ? as you can see my previous comment it didn't respect the line break. it left them as text – John Mar 24 '17 at 13:29
  • @John That's by design. You can't use HTML in comments here. You can insert a newline with Shift+Enter but I don't know if the markdown will respect that; finding out in three, two, one... – 15ee8f99-57ff-4f92-890c-b56153 Mar 24 '17 at 13:31
  • @John No, the markdown doesn't respect newlines in comments. Come to think of it, I should have known that: New users are forever pasting 30-line functions into comments and producing hopeless garble. – 15ee8f99-57ff-4f92-890c-b56153 Mar 24 '17 at 13:31