user1084113
user1084113

Reputation: 962

c# Use of unassigned local variable OR object instance not set to a reference?

The following is a piece of code that does not seem to be working in c# even though it seems acceptable in c++. C# seems to have different standards for object instantiation.

                IList<PointF> vertices = null;

                float radius = (int)(bitmap.Width/3);

                for (double theta = 0; theta < 2 * 3.14; theta += 0.1)
                {
                    PointF temp = new PointF();
                    temp.X = centre.X + radius*((float)(Math.Cos(theta)));
                    temp.Y = centre.Y + radius*((float)(Math.Sin(theta)));
                    vertices.Add(temp);
                }

Where IList is an interface, and PointF is a struct. Tbh I do not know the differences when implementing interfaces vs classes.

If I do not assign "null" to vertices the code does not compile. However, if I do assign null then at runtime I get an error "object instance not set to a reference of an object" (because vertices is declared as null). How can I get around this error?

Upvotes: 0

Views: 1835

Answers (2)

Daniel J.G.
Daniel J.G.

Reputation: 34992

Try creating an instance for vertices that implements IList<PointF>, for example:

IList<PointF> vertices = new List<PointF>();

Upvotes: 0

Erik Schierboom
Erik Schierboom

Reputation: 16636

You have to instantiate the list instance:

IList<PointF> vertices = new List<PointF>();

Upvotes: 6

Related Questions