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.
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With