tags:

views:

126

answers:

3

Why would these lines of code cause that exception

    private Dispatcher dispatcher = null;

    public DownloadManager(Dispatcher dispatcher = null)
    {
        this.dispatcher = dispatcher ?? Dispatcher.CurrentDispatcher;
    }

When the DownloadManager is instantiated in the XAML like

<Window.DataContext>
    <c:DownloadManager />
</Window.DataContext>

?

Note that the debugger doesn't specifically highlight any of these lines; all I know is that if I delete them, my program doesn't crash.

+1  A: 

None that I can see directly, however look in the InnerException if there is one, what does it say?

Preet Sangha
"Object reference not set to an instance of an object." Which means what? `CurrentDispatcher` was not set? But the docs say if that's the case a new one will be created.
Mark
+1  A: 

Just a suggestion. Can you add a default constructor to the class and see what happens? Like so:

public DownloadManager()
{
   this.dispatcher = Dispatcher.CurrentDispatcher;
}

I wonder if XAML doesn't like a constructor with parameters with default values.

Igor Zevaka
Like so? Your sample has an argument ;)
Mark
Of course, copy and paste fail.
Igor Zevaka
You're right, but I think Adam beat you to the punch :)
Mark
Hehe, no worries :)
Igor Zevaka
+2  A: 

To instantiate an object through XAML, it needs to have a public default constructor. A parameterized constructor with default values is not the same as a default constructor. As such, the XAML parser is dying when trying to instantiate your object. I'd say a TargetInvocationException with a NullReferenceException as the inner is a bit worthless and something more useful could be thrown as the inner.

Finally, FWIW, the XAML editor in VS2010 is telling me that my Type is unusable without a default constructor when I have a constructor defined like yours.

Use two constructors instead (or just a default constructor):

public MyViewModel()
    : this( null ) {
}

public MyViewModel( Dispatcher dispatcher = null ) {
    this._dispatcher = dispatcher ?? Dispatcher.CurrentDispatcher;
}
Adam Sills
Yep... you're quite right. I didn't expect there to be a difference (between a default c'tor and one with default args).
Mark
The latter is compiler trick no?
Preet Sangha