0

I am having trouble with some WPF code. This is code I was using previously with another project and it ran fine. I have a class Dots.cs which is a dependency the project containing my main Window1.xaml.cs.

Within Dots.cs I have this function:

    public void MakeDraggable(Canvas theCanvas)
    {
        _canvas = theCanvas;
        _canvas.PreviewMouseDown += DPreviewMouseLeftButtonDown;
    }

I am receiving the InnerException '{System.NullReferenceException: Object reference not set to an instance of an object. at GraphicsBook.Dot.MakeDraggable(Canvas theCanvas) in ...\Dot.cs:line 261 at GraphicsBook.Window1..ctor() in...\Window1.xaml.cs:line 47}

The call to the MakeDraggable method within my Window1.xaml.cs is:

    myDots = new Dot[3];
    myDots[0] = new Dot(new Point(-40, 60));
    myDots[1] = new Dot(new Point(40, 60));
    myDots[2] = new Dot(new Point(40, -60));
    for (int i = 0; i < 3; i++)
    {
        myDots[i].MakeDraggable(gp);
        gp.Children.Add(myDots[i]);
    }

For clarity line 261 in Dot.cs is:

_canvas.PreviewMouseDown += DPreviewMouseLeftButtonDown;

And line 47 in Window1.xaml.cs is:

myDots[i].MakeDraggable(gp);
John Saunders
  • 157,405
  • 24
  • 229
  • 388
petehallw
  • 1,013
  • 6
  • 20
  • 40
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Nov 14 '14 at 17:15

1 Answers1

2

It can be beneficial to validate the arguments to your method before using them. This way, you'll know you've got good values. In your case, there's a good chance that your object gp is null. You can find that out using a breakpoint.

To make it more robust, you can add an argument check to your MakeDraggable like so:

public void MakeDraggable(Canvas theCanvas)
{
    if (theCanvas == null)
    {
        throw new ArgumentNullException("theCanvas");
    }

    _canvas = theCanvas;
    _canvas.PreviewMouseDown += DPreviewMouseLeftButtonDown;
}

Now if you ever call MakeDraggable with null, you'll get the clear Argument Null exception instead of the less descriptive NullReferenceException.

Steve Lillis
  • 3,148
  • 5
  • 18
  • 41