0

Possible Duplicate:
Adding C# labels to a form at Runtime

I can't figure out what is making this error

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

code:

Line[] myLine = new Line[10];
int lineCount = 0;
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
    if (checkBox1.CheckState == CheckState.Checked)
    {
        myLine[lineCount].setPoint(new Point(e.X, e.Y));
        ++pointCount;
        if (pointCount == 2)
        {
            pointCount = 0;
            ++lineCount;
        }
    }
}
0

1 Answer 1

4

Problem is here

myLine[lineCount].setPoint(new Point(e.X, e.Y));

You need to instantiate a new Line type element before using it.

do:

if (checkBox1.CheckState == CheckState.Checked)
    {
        myLine[lineCount] = new Line(); //instantiate the array element
        myLine[lineCount].setPoint(new Point(e.X, e.Y));
        ++pointCount;
        if (pointCount == 2)
        {
            pointCount = 0;
            ++lineCount;
        }
}

It seems that Line is a class, (reference type) if you create an array of reference type then all the elements of the array gets the default value of null, and you can't call a instance method on null object.

Example from MSDN - Single Dimension Arrays

SomeType[] array4 = new SomeType[10];

The result of this statement depends on whether SomeType is a value type or a reference type. If it is a value type, the statement results in creating an array of 10 instances of the type SomeType. If SomeType is a reference type, the statement creates an array of 10 elements, each of which is initialized to a null reference.

Sign up to request clarification or add additional context in comments.

1 Comment

Would be great if the downvoter can point to the mistake ..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.