What is reason for if we move the Button button1 = new Button(); within the constructor. Program is not working. Problem is highlighted.
Why is it called button1 is a private field?
using System;
using System.Windows.Forms;
using System.Drawing;
public class WindowWithButton : Form
{
//Button button1 = new Button();
public WindowWithButton()
{
Button button1 = new Button();
this.Size = new Size(300, 300);
this.Text = "Window Object With Button";
button1.Text = "Press";
this.Controls.AddRange(new System.Windows.Forms.Control[] { this.button1 });
this.button1.Location = new Point(100, 50);
}
public static void Main()
{
Application.Run(new WindowWithButton());
}
}
Loading
VulpesPosted Sep 22, 2014, 5:07 PM
If there isn't, it then looks to see if there's a field or property called button1 and, if there is, it uses that.
If there had been both a field AND a local variable called button1, then the latter would have 'won'.
Posted Sep 22, 2014, 5:31 PM
Posted Sep 22, 2014, 4:45 PM
VulpesPosted Sep 22, 2014, 9:11 AM
If you remove 'this', where highlighted, it will work fine:
Pradeep ShetPosted Sep 22, 2014, 7:18 AM
Because object of button is with in the scope of Constructor.
-Object created with in the scope is local to the block. Once it is out of constructor it will forget the object.
- if you create the Button object out side the constructor, it is local to class and any methods or properties can access that object with in class.
- If you specify public access specifier then it is accessible to all inheriting class as well.
Hope this answered your query. If yes plz mark it answered. Thank you.