Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning C# and objects inside of methods are confusing me

Tags:

c#

.net

I'm sure this question has been answered already, but after an hour of constant searching I'm still very confused.
I'm learning C# and getting used to how things work, but one piece that baffles me is how do I make objects created in a method available to other methods.
I'm working on an app that does some image work. I want to create the objects used by the program when the form loads, then make changes to it with another method. Seems simple enough. Here's the bare bits of the code:

    private void Form1_Load(object sender, EventArgs e)
    {
        InitializeBMPObjects();

    }

    public  void InitializeBMPObjects ()
    {
        Bitmap Bmp1 = new Bitmap(320, 226);        

    }


    public void pushPixels()
    {
        Graphics g = Graphics.FromImage(Bmp1);
        //Do some graphics stuff....

    }

I want to create the bitmap object "Bmp1" then I want pushPixels() to make changes to that Object.
Trouble is, the method pushPixels complains because "The name 'Bmp1' does not exist in the current context"

I believe the issue is basically scope here. That the object Bmp1 only exists inside the scope of the method InitializeBMPObjects. But what if I want to create a bunch of objects on the form load; should I be creating the objects outside of a method? Or do I need to be flagging these as global objects somehow?

Thank you.

like image 374
EtanSivad Avatar asked Jan 14 '23 06:01

EtanSivad


1 Answers

One option is to make that object a member variable, another is to inject it into your method:

public  void InitializeBMPObjects ()
 {
   Bitmap Bmp1 = new Bitmap(320, 226); 
   pushPixels(Bmp1);//bmp1 accessible only to pushPixels in this case
 }
 public void pushPixels(Bitmap bmp1)
 {
   Graphics g = Graphics.FromImage(Bmp1);
   //Do some graphics stuff....
 }

Or..

public class YourClass
{
   private Bitmap bmp1 = new Bitmap(320,226) ;
   //this makes bmp1 accessible to all member methods.
}
like image 118
Lews Therin Avatar answered Jan 23 '23 05:01

Lews Therin