Click here to Skip to main content
15,885,209 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Text;

namespace WindowsFormsApplication3
{
    public class Class1
    {
        public Rectangle[] Snakerec;
        public SolidBrush Brush;

        private int x, y, height, width;

        public void Snake()
        {
            Snakerec = new Rectangle[3];
            Brush = new SolidBrush(Color.Blue);

            x = 20;
            y = 0;
            height = 10;
            width = 10;

            for (int i = 0; i < Snakerec.Length; i++)
            {
                Snakerec[i] = new Rectangle(x, y, width, height);
                x -= 10;
            }
        }
        public void Drawsnake(Graphics paper)
        {
            try
            {
                foreach(Rectangle rec in Snakerec)
                {
                    paper.FillRectangle(Brush, rec);
                }
            }
            catch (Exception ex)
            {
                string st = ex.Message;

            }
        }
    }
}

i write this code in C sharp this error occur in Runtime,,
And Error is "Object reference not set to an instance of an object",,,
Posted
Comments
Sergey Alexandrovich Kryukov 24-Jun-12 3:52am    
What line? Did you try to see it under debugger?
--SA
Arsalaan Ahmed 24-Jun-12 3:53am    
Foreach Loop Show Error "Object reference not set to an instance of an object",,,

1 solution

You don't show the constructor, but I assume that you aren't calling the Snake method before you call the DrawSnake method.
Either make sure you do, or add some defensive code to DrawSnake to ensure that Snakerec is not null before you try to use the foreach.
 
Share this answer
 
Comments
Arsalaan Ahmed 24-Jun-12 4:02am    
Please give me code sample,,
OriginalGriff 24-Jun-12 4:07am    
Um. If you mean the defensive bit, it's pretty simple (and you should do it anyway) - its one line of code:
if (Snakerec != null)
{
foreach (Rectangle...
SoMad 24-Jun-12 6:09am    
Good answer, +5.

Soren Madsen
Sebastian T Xavier 25-Jun-12 1:07am    
my +5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900