title: Create a Graphics Method in a Class?
body: <p>Okay, so I'm creating a class in C#. It works fine, so I'm adding more methods. This is meant to port some BASIC commands as methods into C#. I want to create a method that'll automatically do graphics without having to manually set up pens, points, graphics, etc. Just type in a command. The problem is that...well...it won't work. When I compile, it runs, but it throws an exception when I call the method (<code>Object reference not set to an instance of an object</code>). I know what the exception is telling me, but I can't figure out how to fix it. Here's my current code:</p>
  
  <pre><code>    Graphics g;
  
      public void gpset(int x1, int y1, string colour1)
      {
          Pen myPen = new Pen(Color.FromName(colour1));
          g.DrawLine(myPen, x1, y1, x1 + 1, y1 + 1);
          myPen = new Pen(Color.White);
          g.DrawLine(myPen, x1 + 1, y1, x1 + 1, y1 + 1);
          myPen.Dispose();
          g.Dispose();
      }
  
      public void gline(int x1, int y1, int x2, int y2, string colour1)
      {
          Pen myPen = new Pen(Color.FromName(colour1));
          g.DrawLine(myPen, x1, y1, x2, y2);
          myPen.Dispose();
          g.Dispose();
      }
  
      public void gbox(int x1, int y1, int x2, int y2, string colour1)
      {
          Pen myPen = new Pen(Color.FromName(colour1));
          g.DrawRectangle(myPen, x1, y1, x2, y2);
          myPen.Dispose();
          g.Dispose();
      }
  </code></pre>
  
  <p>Since this didn't work, I tried to do this instead of <code>Graphics g;</code></p>
  
  <pre><code>    PaintEventArgs e;
      Graphics g = e.Graphics();
  </code></pre>
  
  <p>Now it simply won't compile. It says <code>A field initializer cannot reference the non-static field, method, or property 'SmileB.SmileB.e'</code>.</p>
  
  <p>I've also tried doing:</p>
  
  <pre><code>    PaintEventArgs e;
  
      //Later in the code:
      method stuff here()
      {
          other stuff here;
          e.Graphics.&lt;command&gt;;
      }
  </code></pre>
  
  <p>But this doesn't seem to work either. Help? Is this even possible to do? Also, I've run these methods directly inside of a forms application, and they work, so the methods themselves seem not to be the problem.</p>
  
  <p>EDIT: Also, is there a better way to do the <code>gpset</code> method? It should just create one pixel of colour.</p>
  
  <p>EDIT EDIT: Here's how I'm declaring the class:</p>
  
  <pre><code>    using SmileB;
      namespace Drawing_Test
      {
          public partial class Form1 : Form
          {
              SmileB.SmileB ptc = new SmileB.SmileB();
  
              //Down here is where I use the code
          }
      }
  </code></pre>